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

图的深度遍历与广度遍历与二叉树的遍历类似,但是因为是图,需要有个数组存一下点是否被遍历过。

  • 代码实现
/**
 * 源码名称: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();
	}
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/a2bgeek/article/details/38823351
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注