# 【数据结构与算法】图的深度与广度遍历

• 代码实现
/**
* 源码名称：GraphIterateMatrix.java
* 日期：2014-08-25
* 程序功能：图的深度与广度遍历
* 作者：A2BGeek
*/
import java.util.Queue;

public class GraphIterateMatrix {
private String[] Vnode = { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
private int[][] Edge = { { 0, 1, 0, 0, 0, 1, 1, 0, 0 },
{ 1, 0, 1, 0, 0, 0, 1, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 1, 1, 1 }, { 0, 0, 0, 1, 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0, 1, 0, 1, 0 },
{ 0, 0, 0, 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 1, 0, 0, 0, 0, 0 } };
private int nodeNum = Vnode.length;
private boolean[] flag;
private Queue<Integer> queue;// for bfs

public void Dfs() {
flag = new boolean[nodeNum];
for (int i = 0; i < nodeNum; i++) {
if (flag[i] == false) {
DfsRecursive(i);
}
}
}

private void DfsRecursive(int j) {
flag[j] = true;
System.out.print(Vnode[j] + " ");
for (int k = 0; k < nodeNum; k++) {
if (Edge[j][k] == 1 && flag[k] == false) {
DfsRecursive(k);
}
}
}

public void Bfs() {
flag = new boolean[nodeNum];
for (int i = 0; i < nodeNum; i++) {
if (flag[i] == false) {
BfsIterate(i);
}
}
}

private void BfsIterate(int i) {
flag[i] = true;
System.out.print(Vnode[i] + " ");
queue.offer(i);
while (!queue.isEmpty()) {
int j = queue.poll();
for (int k = 0; k < nodeNum; k++) {
if (Edge[j][k] == 1 && flag[k] == false) {
flag[k] = true;
System.out.print(Vnode[k] + " ");
queue.offer(k);
}
}
}

}

public static void main(String[] args) {
GraphIterateMatrix graphIterateMatrix = new GraphIterateMatrix();
graphIterateMatrix.Dfs();
System.out.println();
graphIterateMatrix.Bfs();
}
}
原文作者：数据结构之图
原文地址: https://blog.csdn.net/a2bgeek/article/details/38823351
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。