蓝桥杯:迷宫问题

在这里插入图片描述
如上图的迷宫,入口,出口分别:左上角,右下角
“1"是墙壁,”."是通路
求最短需要走多少步?

public class Maze {
	//from:触发位置  goal:目标位置
	static int f(char[][] data, Set<String> from, String goal) {
		if(from.contains(goal)) return 0;
		Set<String> set = new HashSet<>();
		for(Object obj: from) {
			String[] ss = ((String)obj).split(",");
			int y = Integer.parseInt(ss[0]);
			int x = Integer.parseInt(ss[1]);
			
			if(y>0 && data[y-1][x]=='.') {
				data[y-1][x] = '*';
				set.add(y-1+","+x);
			}
			if(y<data.length-1 && data[y+1][x]=='.') {
				data[y+1][x] = '*';
				set.add(y+1+","+x);
			}
			if(x>0 && data[y][x-1]=='.') {
				data[y][x-1] = '*';
				set.add(y+","+(x-1));
			}
			if(x<data[y].length-1 && data[y][x+1]=='.') {
				data[y][x+1] = '*';
				set.add(y+","+(x+1));
			}
		}
		if(set.isEmpty()) return -1;
		int r = f(data, set, goal);
		if(r<0) return -1;
		return r+1;
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
    	//" +"是一个正则表达式,代表对一个以上的空格进行分割
		String[] ss = sc.nextLine().trim().split(" +");
		int n = Integer.parseInt(ss[0]);
		int m = Integer.parseInt(ss[1]);
		char[][] data = new char[n][m];
		for(int i=0; i<n; i++) {
			data[i] = sc.nextLine().toCharArray();
		}
		sc.close();
		Set<String> set = new HashSet<>();
		set.add("0,0");
		System.out.println(f(data,set,(n-1) +","+(m-1)));
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44260464/article/details/105697620