为此,我编写了这个 javascript,它将一个矩阵(数组的数组)转换为一个无权图。它开始在 4 个方向(上/下/右/左)上导航,而无需走到它已经去的地方。
然后,它会使用 DFS 找到最短路径。
const wall = 0
const flat = 1
const target = 9
// no diagonals
const possibleMoves = [
[-1, 0], // nord
[0, +1],
[+1, 0], // sud
[0, -1],
]
function pathFinder(map) {
const gridW = map[0].length
const gridH = map.length
const start = buildNode([0, 0], map)
const tree = buildTreeMap(start, map, [start])
const path = navigateTree(tree)
console.log(path.map(_ => _.point));
return path.length
// Depth-first search (DFS)
function navigateTree(node) {
const dfp = (acc, _) => {
if (_.value === target) {
acc.push(_)
return acc
}
const targetInMyChildren = _.children.reduce(dfp, [])
if (targetInMyChildren.length > 0) {
targetInMyChildren.unshift(_)
return targetInMyChildren
}
return acc
}
return node.children.reduce(dfp, [])
}
function buildTreeMap(node, map2d, visited) {
const [x, y] = node.point
node.children = possibleMoves
.map((([incx, incy]) => [x + incx, y + incy]))
.filter(([nx, ny]) => {
/**
* REMOVE
* + out of grid
* + walls
* + already visited points
*/
if (nx < 0 || nx >= gridW
|| ny < 0 || ny >= gridH
|| map2d[ny][nx] === wall) {
return false
}
return visited.findIndex(vis => vis.point[0] === nx && vis.point[1] === ny) === -1
})
.map(_ => {
const newNode = buildNode(_, map2d)
visited.push(newNode)
return newNode
})
node.children.forEach(_ => buildTreeMap(_, map2d, visited))
return node
}
}
function buildNode(point, map) {
const value = map[point[1]][point[0]]
return {
point,
value,
children: []
}
}
const stepsCount = pathFinder([
[1, 1, 1, 1],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[0, 1, 1, 1],
[0, 1, 1, 1],
[9, 0, 1, 1],
[1, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 1, 1]
])
console.log(stepsCount);