二维数组,有的值是0,表示可以通过,有的值是1,表示不能通过,从一个顶点出发,从对角线顶点离开,问最短路径有多少条。
明显是图的BFS,一般问的是最短路径有多长,可以采取常规的路径跟踪方法,记录父节点。
这里问的是最短路径有多少条,而且图的BFS要求节点能且只能被访问一次,这里要变化一下,节点可以访问多次,以便统计所有路径。
public class Maze {
public int getSPCount(int[][] a, int m, int n) {
assert(true);
int count = 0;
if(m==0 && n==0){
return 1;
}
if(a[m][n] == 1){
return 0;
}
a[m][n] = 2;
Queue<Point> q = new LinkedList<Point>();
q.add(new Point(0, 0));
q.add(new Point(-1, -1));
boolean stop = false;
while(!q.isEmpty()){
Point p = q.poll();
if(p.x==-1 && p.y==-1){
if(stop) break;
q.add(new Point(-1, -1));
continue;
}
for(int i=1; i<=4; i++){
Point next = getNext(a, p, i);
if(next != null){
if(next.x==-2 && next.y==-2){
count++;
stop = true;
continue;
}else{
q.add(next);
}
}
}
a[p.x][p.y] = 1;
}
return count;
}
public Point getNext(int[][] a, Point p, int direct){
int m = a.length;
int n = a[0].length;
int x = p.x;
int y = p.y;
if(direct==1 && p.x!=0){
x--;
}else if(direct==2 && p.x!=m-1){
x++;
}else if(direct==3 && p.y!=0){
y--;
}else if(direct==4 && p.y!=n-1){
y++;
}
if(x==p.x && y==p.y){
return null;
}else if(a[x][y] == 1){
return null;
}else if(a[x][y] == 2){
return new Point(-2,-2);
}
return new Point(x,y);
}
public class Point{
int x;
int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[][] a = {{0, 0, 0, 1, 0},
{1, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 1, 0}};
Maze o = new Maze();
int count = o.getSPCount(a, 2, 4);
System.out.println(count);
}
}