图的深度与广度优先搜索
package cn.firstflag.crm.service; import java.util.LinkedList; import org.apache.log4j.Logger; public class GraphTest { private Logger log = Logger.getLogger(getClass()); private int n; /** 未联通的权值 */ private int MAX; private int[][] graph; /** 被访问的顶点 */ private int[] visited; public GraphTest() { n = 9; graph = new int[][] { { MAX, MAX, 1, 1, 1, 1, MAX, MAX, MAX }, { MAX, MAX, MAX, MAX, MAX, MAX, 1, MAX, MAX }, { 1, MAX, MAX, MAX, MAX, MAX, MAX, 1, MAX }, { 1, MAX, MAX, MAX, MAX, MAX, MAX, 1, MAX }, { 1, MAX, MAX, MAX, MAX, MAX, MAX, MAX, 1 }, { 1, MAX, MAX, MAX, MAX, MAX, MAX, MAX, 1 }, { 1, MAX, MAX, MAX, MAX, MAX, MAX, MAX, MAX }, { MAX, MAX, 1, 1, MAX, 1, MAX, MAX, MAX }, { MAX, MAX, MAX, MAX, 1, 1, MAX, MAX, MAX }, }; visited = new int[n]; for (int i = 0; i < n; i++) { visited[i] = 0; } } /** * 深度优先搜索 * 1.初始化visited,从v0开始访问 * 2.从未被访问的邻接点开始出发,将与v0路径相同的顶点全部访问 * 3.若图中尚有顶点未被访问,则选择其中一个顶点触发,重复1,2操作 */ public void depthFirstSearch() { for (int i = 0; i< n; i++) { if (visited[i] == 0) { dfs(i); } } } public void dfs(int i) { visited[i] = 1; log.info(i); for (int j = 0; j < n; j++) { if (graph[i][j] != MAX) { dfs(j); } } } /** * 广度优先搜索 */ public void breadthFirstSearch() { LinkedList<Object> que = new LinkedList<>(); for (int i = 0; i < n; i++) { if (visited[i] == 0) { que.add(i); log.info(i); visited[i] = 1; while (!que.isEmpty()) { int node = (int) que.poll(); visited[node] = 1; for (int j = 0; j < n; j++) { if (visited[j] == 0 && graph[node][j] != MAX) { que.add(j); visited[j] = 1; } } } } } } }