1 package cn.itcast.graph;
2
3 import java.util.LinkedList;
4 import java.util.Queue;
5
6 public class DFS {
7 public static void dfsByRecursive(int[][] graph) {
8 int length = graph.length;
9 boolean[] visited = new boolean[length];
10 //如果是连通图
11 //从0号节点开始dfs遍历
12 dfs(graph, 0, visited);
13 //如果是非连通图
14 //需要用一个for循环,确保每一个节点都能被访问到
15 // for (int i = 0; i < length; i++) {
16 // dfs(graph,i,visited)
17 // }
18 }
19
20 public static void dfs(int[][] graph, int vertex, boolean[] visited) {
21 visited[vertex] = true;
22 System.out.print(vertex + " ");
23 int length = graph.length;
24 for (int i = 0; i < length; i++) {
25 if (!visited[i] && graph[vertex][i] == 1) {
26 dfs(graph, i, visited);
27 }
28 }
29 }
30
31 public static void bfsByQueue(int[][] graph) {
32 Queue<Integer> queue = new LinkedList<Integer>();
33 int length = graph.length;
34 boolean[] visited = new boolean[length];
35
36 for (int i = 0; i < length; i++) {
37 if (!visited[i]) {
38 visited[i] = true;
39 System.out.print(i + " ");
40 queue.add(i);
41 while (queue.size() != 0) {
42 Integer temp = queue.poll();
43 for (int j = 0; j < length; j++) {
44 if (!visited[j] && graph[temp][j] == 1) {
45 visited[j] = true;
46 System.out.print(j + " ");
47 queue.add(j);
48 }
49 }
50 }
51 }
52 }
53 }
54
55 public static void main(String[] args) {
56 //定义一个图:使用邻接矩阵
57 int[][] graph = {{0, 1, 0, 0, 1, 0, 0, 0},
58 {0, 0, 1, 1, 0, 0, 0, 0},
59 {0, 0, 0, 1, 0, 0, 0, 0},
60 {0, 0, 0, 0, 0, 0, 0, 0},
61 {0, 0, 0, 0, 0, 1, 0, 1},
62 {0, 0, 0, 0, 0, 0, 1, 0},
63 {0, 0, 0, 0, 0, 0, 0, 0},
64 {0, 0, 0, 0, 0, 0, 0, 0}};
65
66 // int[][] graph = {
67 // { 0, 1, 1, 0, 0 },
68 // { 0, 0, 1, 0, 1 },
69 // { 0, 0, 0, 0, 0 },
70 // { 1, 1, 0, 0, 1 },
71 // { 0, 0, 1, 0, 0 }
72 // };
73
74 dfsByRecursive(graph);
75 System.out.println();
76 bfsByQueue(graph);
77 }
78 }