恭喜解完!!!

我覺得自己的解法滿乾淨漂亮的,分享一下XD

var readline = require('readline');var lines = []
var rl = readline.createInterface({
input: process.stdin
});
rl.on('line', function (line) {
lines.push(line)
});
rl.on('close', function() {
let map = lines.slice(1)
let [h, w] = lines[0].split(' ').map(Number)
let startX = 0
let startY = 0
let endX = w - 1
let endY = h - 1
let ans = []
for(let i=0; i<h; i++) {
ans[i] = []
}
let queue = [{x: startX, y: startY}]
let dir = [
{dx: 1, dy: 0},
{dx: -1, dy: 0},
{dx: 0, dy: 1},
{dx: 0, dy: -1}
]
ans[0][0] = 0
while(queue.length) {
let {x, y} = queue.shift()
for(let d of dir) {
let newX = x + d.dx
let newY = y + d.dy
if (newX >= w || newX < 0 || newY >= h || newY < 0 || map[newY][newX] !== '.') continue
if (ans[y][x] + 1 >= ans[newY][newX] && ans[newY][newX] !== undefined) continue
ans[newY][newX] = ans[y][x] + 1
queue.push({x: newX, y: newY})
}
}
console.log(ans[endY][endX])
})

Written by

重度拖延症患者,興趣是光想不做,有很多想做的事,卻一件都沒有執行。無聊的時候喜歡寫文章,發現自己好像有把事情講得比其他人清楚的能力。相信分享與交流可以讓世界更美好。Medium 文章列表請參考:https://aszx87410.github.io/blog/medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store