【數據結構與算法】圖的深度與廣度遍歷

圖的深度遍歷與廣度遍歷與二叉樹的遍歷類似,但是因爲是圖,需要有個數組存一下點是否被遍歷過。

  • 代碼實現

/**
 * 源碼名稱:GraphIterateMatrix.java 
 * 日期:2014-08-25 
 * 程序功能:圖的深度與廣度遍歷
 * 版權:CopyRight@A2BGeek 
 * 作者:A2BGeek
 */
import java.util.LinkedList;
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 = new LinkedList<Integer>();
		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();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章