题解 | #迷宫问题#

迷宫问题

http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

import java.util.ArrayList; import java.util.List; import java.util.Scanner;

public class Main {

public static void main(String[] args) {
	Scanner in = new Scanner(System.in);
	int n = in.nextInt();
	int m = in.nextInt();
	int[][] map = new int[n][m];
	for(int i=0;i<n;i++) {
		for(int j=0;j<m;j++) {
			map[i][j]=in.nextInt();
		}
	}
	List<Coordinate> pathList = new ArrayList<Coordinate>();
	dfs(map,0,0,pathList);
	for(Coordinate c : pathList) {
		System.out.println("(" + c.x + "," + c.y + ")");
	}
}
static int px[] = {1,0,-1,0};
static int py[] = {0,-1,0,1};
private static boolean dfs(int[][] map,int x,int y,List<Coordinate> pathList) {
	map[x][y] = 1;
	pathList.add(new Coordinate(x,y));
	if(x == map.length-1 && y==map[0].length-1) {
		return true;
	}
	for(int i=0;i<4;i++) {
		if(x+px[i]>=0 && x+px[i]<map.length && y+py[i]>=0 
				&& y+py[i]<map[0].length && map[x+px[i]][y+py[i]] == 0) {
			if(dfs(map,x+px[i],y+py[i],pathList)) {
				return true;
			}
		}
	}
	map[x][y] = 0;
	pathList.remove(pathList.size()-1);
	return false;
}

public static class Coordinate {
	private int x;
	private int y;
	public Coordinate(int x,int y){
		this.x= x;
		this.y= y;
	}	
}

}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务