点击查看:蓝桥杯历年真题 题解目录
迷宫
评测标准答案:31
1.在生成字符数组时,可以直接使用字符串,也可以用 ctr+F 将"U"替换成" 'U', ",
其余三个字符同理,再加上大括号即可。
2. 10x10的数组中的每一个字符都代表一个 人,用嵌套for循环遍历check()每一个字符.
3. 利用一个辅助的数组,做过的位置变为1,如果再次来的1得位置,则说明有循环走不出去
4. 四个方向 每变换一次,i和j变化一次,当i<0,j<0,i>9,j>9时,走迷宫
5. check()每个字符时,都要把辅助数组清零。
import java.util.Scanner;
public class Main001_迷宫{
static int[][] t = new int[10][10];
public static void main(String[] args) {
char dir[][] = new char[][] {
{'U','D','D','L','U','U','L','R','U','L'},
{'U','U','R','L','L','L','R','R','R','U'},
{'R','R','U','U','R','L','D','L','R','D'},
{'R','U','D','D','D','D','U','U','U','U'},
{'U','R','U','D','L','L','R','R','U','U'},
{'D','U','R','L','R','L','D','L','R','L'},
{'U','L','L','U','R','L','L','R','D','U'},
{'R','D','L','U','L','L','R','D','D','D'},
{'U','U','D','D','U','D','U','D','L','L'},
{'U','L','R','D','L','U','U','R','R','R'},
};
int count = 0;
for(int i=0;i<10;i++) {
for(int j=0;j<10;j++){
SetZero(t);
if(check(i,j,dir)) count++;
}
}
System.out.println(count);
}
private static void SetZero(int[][] t2) {
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
t[i][j]=0;
}
private static boolean check(int i,int j,char[][]dir) {
if(i<0||i>9||j<0||j>9) return true;
else if(t[i][j]==1) return false;
else {
t[i][j] = 1;
switch(dir[i][j]){
case 'U':
return check(i-1, j, dir);
case 'D' :
return check(i+1, j, dir);
case 'L' :
return check(i, j-1, dir);
case 'R' :
return check(i, j+1, dir);
default :
return false;
}
}
}
}