蓝桥杯 17省赛 A1 迷宫(dfs)

蓝桥杯 17省赛 A1 迷宫(dfs)

标题:迷宫

X星球的一处迷宫游乐场建在某个小山坡上。
它是由10x10相互连通的小房间组成的。

房间的地板上写着一个很大的字母。
我们假设玩家是面朝上坡的方向站立,则:
L表示走到左边的房间,
R表示走到右边的房间,
U表示走到上坡方向的房间,
D表示走到下坡方向的房间。

X星球的居民有点懒,不愿意费力思考。
他们更喜欢玩运气类的游戏。这个游戏也是如此!

开始的时候,直升机把100名玩家放入一个个小房间内。
玩家一定要按照地上的字母移动。

迷宫地图如下:

UDDLUULRUL
UURLLLRRRU
RRUURLDLRD
RUDDDDUUUU
URUDLLRRUU
DURLRLDLRL
ULLURLLRDU
RDLULLRDDD
UUDDUDUDLL
ULRDLUURRR

=======================

思路:
找到游乐场的边上的可通关的房间
dfs遍历每个边上可通关的房间

public class 细节_1 {
	static char[][] a =new char[10][];
	static boolean[][] b =new boolean[10][10];
	static int ans;
	static int[][] oper = {{1 ,0} ,{-1 ,0} ,{0 ,1} ,{0 ,-1}};
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		for(int i =0 ;i < 10 ;i ++) a[i] =sc.next().trim().toCharArray();
		sc.close();
		for(int i =0 ;i <10 ;i ++) {
			if(a[0][i] =='U') dfs(0 ,i);
			if(a[9][i] =='D') dfs(9 ,i);
			if(a[i][0] =='L') dfs(i ,0);
			if(a[i][9] =='R') dfs(i ,9);
		}
		System.out.println(ans);
	}
	private static void dfs(int y ,int x) {
		if(b[y][x]) return ; else {ans ++ ; b[y][x] =true;}
		
		int y_tmp ,x_tmp;
		for(int i =0 ;i <oper.length ;i ++) {
			y_tmp =y -oper[i][0];
			x_tmp =x -oper[i][1];
			if(y_tmp <0 ||y_tmp >9 ||x_tmp <0 ||x_tmp >9) continue;
			if(a[y_tmp][x_tmp] =='D') if(i !=0) continue;
			if(a[y_tmp][x_tmp] =='U') if(i !=1) continue;
			if(a[y_tmp][x_tmp] =='R') if(i !=2) continue;
			if(a[y_tmp][x_tmp] =='L') if(i !=3) continue;
			dfs(y_tmp ,x_tmp);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43638238/article/details/107751687