[Algorithm Notes] Introduction to Graph Structure and Graph DFS and BFS

Preface: This article will introduce how to deal with the graph structure in the interview, and also briefly introduce BFS and DFS

1. Basic introduction to graphs

basic concept:

  • A graph consists of a set of vertices and a set of edges
  • Although there are concepts of directed graphs and undirected graphs, they can actually be expressed by directed graphs
  • Edges may have weights

The structure of the graph:

  • adjacency list method
  • Adjacency Matrix Method
  • There are many other ways

How to solve the graph interview questions: The graph algorithm is not difficult, but it is very complicated to write the code, and the coding cost is relatively high, so you can deal with the graph interview questions in the following ways

  • First, use your most proficient way to realize the expression of the graph structure
  • Implement all commonly used graph algorithms as templates on a familiar structure
  • Convert the graph structure provided by the interview question into a graph structure you are familiar with, and then call the template or rewrite it (make an adapter)

2. Implementation of the graph

Implementation code:

  • Implementation of point structure

    import java.util.ArrayList;
    
    // 点结构的描述
    public class Node {
          
          
    	// 该点的值
    	public int value;
    	// 该点的入度数
    	public int in;
    	// 该点的出度数
    	public int out;
    	// 该点的相邻点(指该点指向的点)
    	public ArrayList<Node> nexts;
    	// 该点的相邻边(指该点指向的边)
    	public ArrayList<Node> edges;
    
    	public Node(int value) {
          
          
    		this.value = value;
    		in = 0;
    		out = 0;
    		nexts = new ArrayList<>();
    		edges = new ArrayList<>();
    	}
    }
    
  • Implementation of Edge Structure

    // 边结构的描述
    public class Edge {
          
          
    	// 边的权重
    	public int weight;
    	// 入边节点
    	public Node from;
    	// 出边节点
    	public Node to;
    
    	public Edge(int weight, Node from, Node to) {
          
          
    		this.weight = weight;
    		this.from = from;
    		this.to = to;
    	}
    }
    
  • Implementation of graph structure

    import java.util.HashMap;
    import java.util.HashSet;
    
    // 图的描述
    public class Graph {
          
          
    	// 点的集合,Integer 表示节点的值,先有值,再创建节点
    	public HashMap<Integer, Node> nodes;
    	// 边的集合
    	public HashSet<Edge> edges;
    
    	public Graph() {
          
          
    		nodes = new HashMap<>();
    		edges = new HashSet<>();
    	}
    }
    

Diagram structure of common interview questions:

  • Represented by a two-dimensional array, each one-dimensional array has three values
  • The first value represents the weight of the edge
  • The second value represents the starting node of the edge
  • The third value represents the destination node of the edge

Suppose an existing array representation is like this: { {3, 0, 7}, {5, 1, 2}, {6, 2, 7}}, which conforms to the structure of the above figure, then it is represented as follows

img

When we interview a graph with this structure, we can use the structure of the graph we have defined above to represent it, so we only need to do another adaptation process

Adaptation code:

public class Create {
    
    
	
	public static Graph createGraph(int[][] matrix) {
    
    
		Graph graph=new Graph();
		for(int i=0;i<matrix.length;i++) {
    
    
			// 边的权重
			int weight=matrix[i][0];
			// 出发节点的值
			int from=matrix[i][1];
			// 目的节点的值
			int to=matrix[i][2];
			// 如果该图中还没有包含该节点,则将节点入图
			if(!graph.nodes.containsKey(from)) {
    
    
				graph.nodes.put(from, new Node(from));
			}
			if(!graph.nodes.containsKey(to)) {
    
    
				graph.nodes.put(to, new Node(to));
			}
			Node fromNode=graph.nodes.get(from);
			Node toNode=graph.nodes.get(to);
			Edge edge=new Edge(weight,fromNode,toNode);
			fromNode.out++;
			toNode.in++;
			fromNode.nexts.add(toNode);
			fromNode.edges.add(edge);
			graph.edges.add(edge);
		}
		return graph;
	}
}

3. BFS

BFS method:

Pop the top-level node from the graph, using aCollection Setregister the node, then enter the node intoqueue. When we pop it from the queue, put its adjacent node (pointed node) into the queue, but first we need to determine whether the adjacent node is registered in the set, if it is registered, it will not be processed; if it is not registered , register and queue the node. Then repeat the operation just now, traversing each layer

Method template:

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class BFS {
    
    
	// BFS 需要有一个头节点
	public static void bfs(Node start) {
    
    
		if (start == null) {
    
    
			return;
		}
		Queue<Node> queue = new LinkedList<>();
		HashSet<Node> set = new HashSet<>();
		queue.add(start);
		set.add(start);
		while (!queue.isEmpty()) {
    
    
			Node node = queue.poll();
			System.out.println(node.value);
			for (Node cur : node.nexts) {
    
    
				if (!set.contains(cur)) {
    
    
					set.add(cur);
					queue.add(cur);
				}
			}
		}
	}
}

4. DFS

DFS method:

A road goes to the end, but a loop cannot be formed. When it reaches the end, it returns to the previous node. If there is no other way to the node, it continues to go up. When a node has other paths, first determine whether the new node has been printed, and continue to go up until a new node is found and has not been printed. When the head node is finally returned, the depth traversal ends. which useCollection Setto mark whether the node has been walked or printed, usestackto store the node of the current traversal route

Method template:

import java.util.HashSet;
import java.util.Stack;

public class DFS {
    
    

	public static void dfs(Node node) {
    
    
		if (node == null) {
    
    
			return;
		}
		Stack<Node> stack = new Stack<>();
		HashSet<Node> set = new HashSet<>();
		stack.add(node);
		set.add(node);
		// 在入栈时就进行打印
		System.out.println(node.value);
		while (!stack.isEmpty()) {
    
    
			Node cur = stack.pop();
			for (Node next : cur.nexts) {
    
    
				if (!set.contains(next)) {
    
    
					stack.add(cur);
					stack.add(next);
					set.add(next);
					System.out.println(next.value);
					break;
				}
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/weixin_51367845/article/details/123243184