一.广度遍历
二.代码实现
三.总结
一.广度遍历
基本思路
广度优先搜索类似于树的层次遍历过程。它需要借助一个队列来实现。
具体过程如下:
1.准备工作:创建一个 tempVisitedArray数组,用来记录已被访问过的顶点;创建一个队列,用来存放每一层的顶点;初始化图G。
2.从图中的任意某一点开始访问,将的它对应的tempVisitedArray数组的值设置为true,同时将该顶点入队。
3.只要队列不空,则重复如下操作:
(1)队头顶点u出队。
(2)依次检查u的所有邻接顶点w,若tempVisitedArray[w]的值为false,则访问w,并将visited[w]置为true,同时将w入队。
我们这里需要做两个if判断:是否邻接和是否访问过
//check the node is visited or not.
if (tempVisitedArray[i]) {
continue;
}//of if
//check the node is directed or not.
if (connectivityMatrix.getData()[tempIndex][i] == 0) {
continue;
}//of if
二.代码展示
关键代码
/**
* Broad Traversal
*
* @param paramStartIndex the given start index.
* @return the sequence of the traversal.
*/
public String BroadTraversal(int paramStartIndex) {
CircleObjectQueue temObjectQueue = new CircleObjectQueue();
String resultString = "";
int tempNumNodes = connectivityMatrix.getRows();
boolean[] tempVisitedArray = new boolean[tempNumNodes];
//initialize the queue
tempVisitedArray[paramStartIndex] = true;
temObjectQueue.enqueue(new Integer(paramStartIndex));
int tempIndex;
Integer tempInteger = (Integer) temObjectQueue.dequeue();
resultString += tempInteger.intValue();
while (tempInteger != null) {
tempIndex = tempInteger.intValue();
//find the total nodes linked .
for (int i = 0; i < tempNumNodes; i++) {
//check the node is visited or not.
if (tempVisitedArray[i]) {
continue;
}//of if
//check the node is directed or not.
if (connectivityMatrix.getData()[tempIndex][i] == 0) {
continue;
}//of if
//fine the directed and unvisited nodes.
tempVisitedArray[i] = true;
temObjectQueue.enqueue(new Integer(i));
resultString += i;
}//of for i
//take the head from the queue.
tempInteger = (Integer) temObjectQueue.dequeue();
}//of while
return resultString;
}//of BroadTraversal
注意while和for循环的顺序,我们只有在判断了队列不空的前提下,才能出队队头元素和访问它所有的邻接节点(这里即用for循环).
测试代码
/**
* Unit test for BroadTraversal
*/
public static void BroadTraversalTest() {
//Test an undirected graph.
int[][] tempMatrix = {{0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0}};
Graph tempGraph = new Graph(tempMatrix);
System.out.println(tempGraph);
String tempSequence = "";
try {
tempSequence = tempGraph.BroadTraversal(2);
} catch (Exception e) {
System.out.println(e);
}//of try
System.out.println("The broad traversal is " + tempSequence);
}//of BroadTraversalTest