走迷宫

二维数组,有的值是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);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值