图的深度优先搜索(DFS)和广度优先搜索(BFS)
/** * */ package java_graph; import java.util.LinkedList; /** * @author clydelou * */ public class Graph { /** * @param args */ static boolean[] flag; public static int first_adj_vex(int[][] g, int v) { int j = g[0].length; for (int k = 0; k < j; k++) { if (g[v - 1][k] != 0) { return k + 1; } } return 0; } public static int next_adj_vex(int[][] g, int v, int w) { int j = g[0].length; for (int k = w; k < j; k++) { if (g[v - 1][k] != 0) { return k + 1; } } return 0; } public static void dfs_traverse(int[][] g) { for (int v = 1; v <= g.length; v++) { if (!flag[v - 1]) { dfs(g, v); } } System.out.println(); } public static void dfs(int[][] g, int v) { flag[v - 1] = true; System.out.print(v + "/t"); for (int w = first_adj_vex(g, v); w > 0; w = next_adj_vex(g, v, w)) { if (!flag[w - 1]) { dfs(g, w); } } } public static void bfs_traverse(int[][] g) { LinkedList<Integer> list = new LinkedList<Integer>(); for (int v = 1; v <= g.length; v++) { if (!flag[v - 1]) { flag[v - 1] = true; System.out.print(v + "/t"); list.addLast(v); while (!list.isEmpty()) { int u = list.removeFirst(); for (int w = first_adj_vex(g, u); w > 0; w = next_adj_vex( g, u, w)) { if (!flag[w - 1]) { flag[w - 1] = true; System.out.print(w + "/t"); list.addLast(w); } } } } } System.out.println(); } public static void print_graph(int[][] g) { int i = g.length; int j = g[0].length; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { System.out.print(g[m][n] + "/t"); } System.out.println(); } } public static void main(String[] args) { // TODO Auto-generated method stub int[][] g = { { 0, 1, 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 1, 1, 0, 0, 0 }, { 1, 0, 0, 0, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0, 0, 0, 1 }, { 0, 1, 0, 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0, 0, 1, 0 }, { 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 1, 0, 0, 0 } }; System.out.println("Graph:"); print_graph(g); flag = new boolean[g.length]; System.out.print("DFS:"); dfs_traverse(g); flag = new boolean[g.length]; System.out.print("BFS:"); bfs_traverse(g); } }
运行结果:
Graph: 0 1 1 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 DFS:1 2 4 8 5 3 6 7 BFS:1 2 3 4 5 6 7 8