地牢逃脱
题目描述
给定一个 n 行 m 列的地牢,其中 '.' 表示可以通行的位置,'X' 表示不可通行的障碍,牛牛从 (x0 , y0 ) 位置出发,遍历这个地牢,和一般的游戏所不同的是,他每一步只能按照一些指定的步长遍历地牢,要求每一步都不可以超过地牢的边界,也不能到达障碍上。地牢的出口可能在任意某个可以通行的位置上。牛牛想知道最坏情况下,他需要多少步才可以离开这个地牢。
输入描述:
每个输入包含 1 个测试用例。每个测试用例的第一行包含两个整数 n 和 m(1 <= n, m <= 50),表示地牢的长和宽。接下来的 n 行,每行 m 个字符,描述地牢,地牢将至少包含两个 '.'。接下来的一行,包含两个整数 x0
, y0
,表示牛牛的出发位置(0 <= x0 < n, 0 <= y0 < m,左上角的坐标为 (0, 0),出发位置一定是 '.')。之后的一行包含一个整数 k(0 < k <= 50)表示牛牛合法的步长数,接下来的 k 行,每行两个整数 dx, dy 表示每次可选择移动的行和列步长(-50 <= dx, dy <= 50)
输出描述:
输出一行一个数字表示最坏情况下需要多少次移动可以离开地牢,如果永远无法离开,输出 -1。以下测试用例中,牛牛可以上下左右移动,在所有可通行的位置.上,地牢出口如果被设置在右下角,牛牛想离开需要移动的次数最多,为3次。
示例1
输入
3 3 ... ... ... 0 1 4 1 0 0 1 -1 0 0 -1
输出
3
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.util.LinkedList; 4 import java.util.Queue; 5 6 public class Main { 7 public static void main(String[] args) throws Exception { 8 BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 9 String[] dyh = read.readLine().split(" "); // 第一次输入的数据 10 int n = Integer.parseInt(dyh[0]); 11 int m = Integer.parseInt(dyh[1]); 12 char[][] wz = new char[n][m]; 13 for (int i = 0; i < n; i++) { 14 String th = read.readLine(); 15 th = th.replace(" ", ""); 16 wz[i] = th.toCharArray(); 17 } 18 String[] cfdd = read.readLine().split(" "); 19 int n1 = Integer.parseInt(cfdd[0]); 20 int n2 = Integer.parseInt(cfdd[1]); 21 if (n1 >= n || n2 >= m) { 22 System.out.println(-1); 23 return; 24 } 25 26 int bf = Integer.parseInt(read.readLine()); // 输入的步伐 27 int[][] wzxx = new int[bf][2]; 28 for (int i = 0; i < bf; i++) { 29 String[] wzstr = read.readLine().split(" "); 30 for (int j = 0; j < wzstr.length; j++) { 31 wzxx[i][0] = Integer.parseInt(wzstr[0]); 32 wzxx[i][1] = Integer.parseInt(wzstr[1]); 33 } 34 } 35 int[][] daz = new int[n][m]; 36 Queue<Integer> queueX = new LinkedList<Integer>(); 37 Queue<Integer> queueY = new LinkedList<Integer>(); 38 daz[n1][n2] = 1; 39 queueX.offer(n1); 40 queueY.offer(n2); 41 while (!queueX.isEmpty() && !queueY.isEmpty()) { 42 int x = queueX.poll(); 43 int y = queueY.poll(); 44 for (int i = 0; i < bf; i++) { 45 int x1 = x + wzxx[i][0]; 46 int y1 = y + wzxx[i][1]; 47 if (x1 >= 0 && y1 >= 0 && x1 < n && y1 < m) { 48 if (daz[x1][y1] == 0) { 49 if (wz[x1][y1] == '.') { 50 queueX.offer(x1); 51 queueY.offer(y1); 52 daz[x1][y1] = daz[x][y] + 1; 53 54 } else { 55 daz[x1][y1] = 0; 56 } 57 } 58 } 59 60 } 61 } 62 int da = 0; 63 boolean boo = false; 64 for (int i = 0; i < n; i++) { 65 for (int k = 0; k < m; k++) { 66 if (daz[i][k] == 0 && wz[i][k] == '.') { 67 da = 0; 68 boo = true; 69 break; 70 } else { 71 da = Math.max(da, daz[i][k]); 72 } 73 } 74 if (boo) { 75 break; 76 } 77 } 78 System.out.println(da - 1); 79 } 80 }

浙公网安备 33010602011771号