题解 | #走迷宫#
走迷宫
http://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
var lines = []
while(line = readline()) {
lines.push(line)
}
let line1=lines[0].split(' ');
var n=Number(line1[0]),m=Number(line1[1]);
let line2=lines[1].split(' ');
var map=new Array(n);
for(let i=0;i<n;i++){
map[i]=lines[i+2].split('');
}
let target = false;
map[Number(line2[0])-1][Number(line2[1])-1]=0;
function bfs(queue) {
const nextQueute = [];
if(queue.length === 0) return;
if(target) return;
let dep =map[queue[0][0]][queue[0][1]];
let dx=[0, 0 ,1 ,-1],dy=[1,-1,0,0];
for(let j=0;j<queue.length;j++) {
for(let i = 0;i<4;i++) {
let ni=dx[i]+queue[j][0],nj=dy[i]+queue[j][1];
if(ni<0 || ni>=n || nj<0 || nj>=m) continue;
if(map[ni][nj] === '.') {
map[ni][nj]=dep+1;
if(ni === Number(line2[2])-1 && nj === Number(line2[3])-1) target = true;
nextQueute.push([ni,nj]);
}
}
}
if(nextQueute.length && !target) bfs(nextQueute);
}
let queee=[[Number(line2[0])-1,Number(line2[1])-1]];
bfs(queee);
if(map[Number(line2[2])-1][Number(line2[3])-1] !== '.' && map[Number(line2[2])-1][Number(line2[3])-1] !== '*') {
print(map[Number(line2[2])-1][Number(line2[3])-1])
}else{
print(-1)
}