Java中的深度優(yōu)先遍歷和廣度優(yōu)先遍歷都是常用的圖遍歷算法,目的是遍歷這個圖或樹的所有節(jié)點(diǎn)
深度優(yōu)先遍歷是一種遞歸的算法,從當(dāng)前節(jié)點(diǎn)出發(fā),優(yōu)先遍歷其子節(jié)點(diǎn),直到?jīng)]有子節(jié)點(diǎn)為止,然后回溯到上一個未遍歷的節(jié)點(diǎn),繼續(xù)遍歷其子節(jié)點(diǎn),直到遍歷完整個圖。以下是深度優(yōu)先遍歷的Java代碼示例:
public void dfs(int[][] graph, int start, boolean[] visited) { visited[start] = true; System.out.print(start + " "); for (int i = 0; i< graph.length; i++) { if (graph[start][i] == 1 && !visited[i]) { dfs(graph, i, visited); } } }
廣度優(yōu)先遍歷是一種使用隊(duì)列的算法,從當(dāng)前節(jié)點(diǎn)出發(fā),先訪問相鄰的所有節(jié)點(diǎn),然后將這些相鄰節(jié)點(diǎn)入隊(duì)列,繼續(xù)訪問隊(duì)列中的節(jié)點(diǎn),直到隊(duì)列為空,這時候我們就遍歷完了整個圖。以下是廣度優(yōu)先遍歷的Java代碼示例:
public void bfs(int[][] graph, int start, boolean[] visited) { Queuequeue = new LinkedList<>(); queue.add(start); visited[start] = true; while (!queue.isEmpty()) { int currentNode = queue.poll(); System.out.print(currentNode + " "); for (int i = 0; i< graph.length; i++) { if (graph[currentNode][i] == 1 && !visited[i]) { queue.add(i); visited[i] = true; } } } }