手機做任務(wù)網(wǎng)站有哪些/百度賬號免費注冊
文章目錄
- 1. 代碼倉庫
- 2. 廣度優(yōu)先遍歷圖解
- 3.主要代碼
- 4. 完整代碼
1. 代碼倉庫
https://github.com/Chufeng-Jiang/Graph-Theory
2. 廣度優(yōu)先遍歷圖解
3.主要代碼
- 原點入隊列
- 原點出隊列的同時,將與其相鄰的頂點全部入隊列
- 下一個頂點出隊列
- 出隊列的同時,將與其相鄰的頂點全部入隊列
private void bfs(int s){ //使用循環(huán)Queue<Integer> queue = new LinkedList<>();queue.add(s);visited[s] = true;while(!queue.isEmpty()){ //只要不是空就不停地出隊int v = queue.remove(); // v記錄隊首元素 | 相鄰頂點入隊后,重新進入while循環(huán),隊首出隊order.add(v); //添加到order數(shù)組中,order數(shù)組裝的是按照BFS順序遍歷的頂點for(int w: G.adj(v))if(!visited[w]){queue.add(w); // 相鄰的頂點入隊列visited[w] = true;}}
}
復(fù)雜度:O(V+E)
4. 完整代碼
輸入文件
7 9
0 1
0 3
1 2
1 6
2 3
2 5
3 4
4 5
5 6
package Chapt04_BFS_Path._0401_Graph_BFS_Queue;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;public class GraphBFS {private Graph G;private boolean[] visited;private ArrayList<Integer> order = new ArrayList<>(); // 存儲遍歷順序public GraphBFS(Graph G){this.G = G;visited = new boolean[G.V()];//遍歷所有連通分量for(int v = 0; v < G.V(); v ++)if(!visited[v])bfs(v);}private void bfs(int s){ //使用循環(huán)Queue<Integer> queue = new LinkedList<>();queue.add(s);visited[s] = true;while(!queue.isEmpty()){ //只要不是空就不停地出隊int v = queue.remove(); // v記錄隊首元素 | 相鄰頂點入隊后,重新進入while循環(huán),隊首出隊order.add(v); //添加到order數(shù)組中,order數(shù)組裝的是按照BFS順序遍歷的頂點for(int w: G.adj(v))if(!visited[w]){queue.add(w); // 相鄰的頂點入隊列visited[w] = true;}}}//取出遍歷順序public Iterable<Integer> order(){return order;}public static void main(String[] args){Graph g = new Graph("g1.txt");GraphBFS graphBFS = new GraphBFS(g);System.out.println("BFS Order : " + graphBFS.order());}
}