package wangyi;
/**
* Created by Administrator on 2016/12/7.
* 給定一個 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次。
*/
import java.util.*;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while (in.hasNext()) {//注意while處理多個case
int x=in.nextInt();
int y=in.nextInt();
char[][] points=new char[x][y];
int[][] tar=new int[x][y];
for(int i=0;i<x;i++){
String str=in.next();
points[i]=str.toCharArray();
}
int startx=in.nextInt();
int starty=in.nextInt();
int k=in.nextInt();
int[] stepx=new int[k];
int[] stepy=new int[k];
for(int i=0;i<k;i++){
stepx[i]=in.nextInt();
stepy[i]=in.nextInt();
}
Queue<Integer> xqueue=new LinkedList<Integer>();
Queue<Integer> yqueue=new LinkedList<Integer>();
//引入隊列是爲了遍歷到最後不能走爲止
xqueue.add(startx);
yqueue.add(starty);
tar[startx][starty]=1; //起始點訪問標記;1表示已經訪問
while(!xqueue.isEmpty()&&!yqueue.isEmpty()){
startx=xqueue.remove(); //取隊首
starty=yqueue.remove();
for(int i=0;i<k;i++){
if(startx+stepx[i]<x&&startx+stepx[i]>=0&&starty+stepy[i]<y&&starty+stepy[i]>=0) //不出界
if(tar[startx+stepx[i]][starty+stepy[i]]==0){
if(points[startx+stepx[i]][starty+stepy[i]]=='.'){
tar[startx+stepx[i]][starty+stepy[i]]=tar[startx][starty]+1;
xqueue.add(startx+stepx[i]);
yqueue.add(starty+stepy[i]);
}
else
tar[startx+stepx[i]][starty+stepy[i]]=-1; //訪問點爲X
}
}
}
int max=0;
int getRoad=1;
for(int i=0;i<x;i++)
for(int j=0;j<y;j++){
if(points[i][j]=='.'&&tar[i][j]==0){
getRoad=0; //有存在沒有被訪問的“.”說明不能遍歷完全,有些出口到不了。
}
max=Math.max(max, tar[i][j]);
}
if(getRoad==0)
System.out.println(-1);
else
System.out.println(max-1);
}
}
}
網易面試題之給定一個 n 行 m 列的地牢,其中 '.' 表示可以通行的位置,'X' 表示不可通行的障礙,牛牛從 (x0 , y0 ) 位置出發,遍歷這個地牢, * 和一般的遊戲所不同的是,他每一步
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.