node , bfs, , node ( , ):
package stackoverflow;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class BFSTest {
public static class BFSNode {
public int node, depth;
public BFSNode parent;
public BFSNode(int node) {
this.node = node;
this.depth = 0;
this.parent = null;
}
public BFSNode(int node, BFSNode parent) {
this.node = node;
this.depth = parent.depth+1;
this.parent = parent;
}
}
ArrayDeque<BFSNode> queue;
int[][] arr;
public BFSTest() {
queue = new ArrayDeque<BFSNode>();
arr = new int[5][5];
arr[0][1] = arr[0][3] = arr[0][4] = 1;
arr[1][2] = 1;
arr[2][3] = arr[2][4] = 1;
arr[3][2] = arr[3][4] = 1;
arr[4][1] = 1;
}
public int bfs(int src, int dest, int maxDepth){
int i;
int countPaths = 0;
BFSNode element;
queue.add(new BFSNode(src));
while(!queue.isEmpty())
{
element = queue.poll();
if (element.depth > maxDepth)
break;
i = 0;
while(i < 5)
{
if(arr[element.node][i] > 0)
{
if(i == dest && element.depth +1 <= maxDepth) {
BFSNode tmp = element;
List<Integer> path = new ArrayList<Integer>();
path.add(dest);
while (tmp != null) {
path.add(tmp.node);
tmp = tmp.parent;
}
for (int j = path.size() - 1; j >= 0; j--) {
System.out.print(path.get(j) + " ");
}
System.out.println();
countPaths++;
}
queue.add(new BFSNode(i, element));
}
i++;
}
}
queue.clear();
return countPaths;
}
public static void main(String[] args) {
BFSTest test = new BFSTest();
System.out.println(test.bfs(2, 2, 3));
System.out.println(test.bfs(0, 2, 3));
}
}
2 3 2
2 4 1 2
2
0 1 2
0 3 2
0 4 1 2
3