- 对于广度优先遍历,使用递归方式实现非常普遍,这里我们讨论一下如何使用非递归来实现
算法
- 1、以图的邻接矩阵为例
- 2、使用一个queue来保存访问顺序,每次取队首元素,如果其有邻接点,则将其所有邻接点入队,并设置visit数组为1,最后再将其出队
- 3、循环结束条件为:队列为空
代码实现
以下图为例
public class BfsIterateAdjacentMatrix {
private static Map<Integer, String> idVertexMap = new HashMap<Integer, String>(){{
put(0,"V0");
put(1,"V1");
put(2,"V2");
put(3,"V3");
put(4,"V4");
put(5,"V5");
put(6,"V6");
put(7,"V7");
}};
private static int[][] adjacentMatrix = new int[][]{
{0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 0, 0, 0},
};
private static int[] visited = new int[adjacentMatrix.length];
public static void main(String[] args){
bfs();
}
private static void bfs(){
Queue<Integer> visitQueue = new LinkedBlockingQueue<>();
visitQueue.add(0);
int lineNo = 0;
visited[lineNo] = 1;
while (!visitQueue.isEmpty()){
lineNo = visitQueue.peek();
System.out.println("visit: " + idVertexMap.get(lineNo));
for (int colNo =0; colNo < adjacentMatrix.length; colNo++){
if (visited[colNo] ==0 && adjacentMatrix[lineNo][colNo]==1){
visitQueue.add(colNo);
visited[colNo]=1;
}
}
visitQueue.poll();
}
}
}