MCPcopy
hub / github.com/wangzheng0822/algo / bfs

Method bfs

java/30_graph/Graph.java:34–62  ·  view source on GitHub ↗
(int s, int t)

Source from the content-addressed store, hash-verified

32 }
33
34 public void bfs(int s, int t) {
35 if (s == t) return;
36 // visited是用来记录已经被访问的顶点,用来避免顶点被重复访问。
37 boolean[] visited = new boolean[v];
38 visited[s] = true;
39 // queue是一个队列,用来存储已经被访问、但相连的顶点还没有被访问的顶点。
40 Queue<Integer> queue = new LinkedList<>();
41 queue.add(s);
42 // prev用来记录搜索路径。
43 int[] prev = new int[v];
44 for (int i = 0; i < v; ++i) {
45 prev[i] = -1;
46 }
47 while (queue.size() != 0) {
48 int w = queue.poll();
49 for (int i = 0; i < adj[w].size(); ++i) {
50 int q = adj[w].get(i);
51 if (!visited[q]) {
52 prev[q] = w;
53 if (q == t) {
54 print(prev, s, t);
55 return;
56 }
57 visited[q] = true;
58 queue.add(q);
59 }
60 }
61 }
62 }
63
64 private void print(int[] prev, int s, int t) { // 递归打印 s->t 的路径
65 if (prev[t] != -1 && t != s) {

Callers

nothing calls this directly

Calls 4

printMethod · 0.95
addMethod · 0.45
sizeMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected