题目大致如下:
输入n,m,为地牢长和宽,下面输入n行m列的字符,如果为‘.’那么代表此处可以通行,否则无法通行,接下去,代表,地牢入口在哪,输入一行X,Y。代表入口地址,接下面是有几种走法,输入一个数字numb,下面每行有2个数字,代表如何行走。默认出口为右下角。求最坏情况下多少次能找到出口。
输入事例:
3 3
. . .
. . .
. . .
0 1
4
0 1
1 0
-1 0
0 -1
输出:
3
我用dfs搜索整个地牢,如果找到出口,就记录行走的步数,最后求所有解中的最大值即可。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class 地牢逃脱 {
static ArrayList<Integer> ans = new ArrayList<Integer>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
// 1<=n,m<=50
char[][] d = new char[n][m];
boolean[][] is = new boolean[n][m];
// 边界这儿在0<=n,m<=49
// 初始化地牢
for (int i = 0; i < n; i++) {
String stdin = sc.next();
for (int j = 0; j < m; j++) {
d[i][j] = stdin.toCharArray()[j];
is[i][j] = false;
}
}
// 初始化其实位置
int startx = sc.nextInt();
int starty = sc.nextInt();
// 方向次数
int t = sc.nextInt();
// 初始化上下左右,用数组方便遍历
int[][] dir = new int[t][2];
for (int i = 0; i < t; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
dir[i][0] = x;
dir[i][1] = y;
}
dfs(d, dir, startx, starty, 0, is);
try {
Collections.sort(ans);
System.out.println(ans.get(0));
} catch (Exception e) {
System.out.println(-1);
}
}
public static void dfs(char[][] d,int[][] dir,int x,int y,int count,boolean[][] is){
is[x][y] = true;
if(x == d.length-1 && y == d[0].length-1 ){
ans.add(count);
return;
}
for (int i = 0; i < dir.length; i++) {
if(x+dir[i][0] < d.length && x + dir[i][0] >= 0 && y + dir[i][1] < d[0].length
&& y+dir[i][1] >= 0 && d[x+dir[i][0]][y+dir[i][1]] == '.' && is[x+dir[i][0]][y+dir[i][1]] == false)
{
dfs(d,dir,x+dir[i][0],y+dir[i][1],count+1,is);
}
}
is[x][y] = false;
}
}