图的遍历算法总结
图的遍历算法
- 邻接表定义
static Vnode[] vnodes;
/** 邻接表 <表头结点>
* 下标就是表示 结点号*/
static class Vnode {
int degree = 0;
Node point = null;
}
/** 结点 */
static class Node {
int id;
Node next = null;
Node(int id, Node next){
this.id = id;
this.next = next;
}
}
- 邻接矩阵定义
采用二维数组
/** 点数, 边数*/
static int Nv, Ne;
static int[][] G;
邻接表- 递归
1. DFS
/** 判断图是否连通 DFS 递归算法*/
static void DFS(boolean[] visit, int start) {
visit[start] = true;
Node node = vnodes[start].point;
while(node != null) {
if(visit[node.id] == false) { // 未访问
DFS(visit, node.id);
}
node = node.next;
}
}
邻接表- 递归
2. BFS
在这里插入代码片
邻接表- 非递归
1. DFS
邻接表- 非递归
2. BFS
邻接矩阵- 递归
1. DFS
/**
* DFS 递归
* @param head
* @param v 是否访问过
*/
static void DFSRecursion(int head, int[] v){
v[head] = 1;
System.out.print(head + " ");
for (int i = 0; i < Nv; i++){
/** 没有访问过, 并且是邻接点*/
if ( v[i] == 0 && G[head][i] == 1){
DFSRecursion(i, v);
}
}
}
邻接矩阵- 递归
2. BFS
在这里插入代码片
邻接矩阵- 非递归
- DFS
/**
* 非递归 DFS
*/
static void DFSTravel(){
int[] visited = new int[Nv];
for(int i = 0; i < Nv; i++){
if(visited[i] == 0) { // 可能图不连通
DFS(i,visited);
}
}
}
static void DFS(int head, int[] v){
Stack<Integer> stack = new Stack<>();
System.out.print("{ ");
stack.push(head);
v[head] = 1; // 起点已经访问了
System.out.print(head + " ");
while(!stack.isEmpty()){
for (int i = 0; i < Nv; i++){
/** 没有访问过, 并且是邻接点*/
if ( v[i] == 0 && G[head][i] == 1){
stack.push(i);
v[i] = 1;
System.out.print(stack.peek() + " ");
break;
}
}
if (head == stack.peek()){ /* 没有邻接点了*/
stack.pop();
}else { /* 有邻接点*/
head = stack.peek();
}
}
System.out.println("}");
}
邻接矩阵- 非递归
2. BFS
/**
* 非递归 BFS
*/
static void BFSTravel(){
int[] visited = new int[Nv]; /*开始都未访问过*/
for(int i = 0; i < Nv; i++){ /*访问每一个结点*/
if(visited[i] == 0) //可能图不连通
BFS(i,visited);
}
}
static void BFS(int head, int[] v){
Queue<Integer> queue = new LinkedList<>();
System.out.print("{ ");
queue.add(head);
v[head] = 1;
while (!queue.isEmpty()){
head = queue.peek();
for (int i = 0; i < Nv; i++){ /* head 的邻接点入队列*/
/** 没有访问过, 并且是邻接点*/
if ( v[i] == 0 && G[head][i] == 1){
v[i] = 1;
queue.add(i);
}
}
System.out.print(queue.peek() + " ");
if (!queue.isEmpty()){
queue.poll();
}
}
System.out.println("}");
}