Last active
January 31, 2016 22:28
-
-
Save karenpeng/d3e30500cf9b6dafb7fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var assert = require('assert') | |
var maze = [ | |
[1,0,1,1,0], | |
[1,0,1,0,0], | |
[1,0,0,0,0], | |
[1,0,0,0,0] | |
] | |
// http://www.cnblogs.com/biyeymyhjob/archive/2012/07/31/2615833.html | |
assert.equal(path(maze, [0, 1], [1, 3]), 6); | |
//https://en.wikipedia.org/wiki/A*_search_algorithm | |
function path(maze, start, end){ | |
return bfs(maze, start, end) | |
} | |
function bfs(maze, start, end){ | |
var result = 0 | |
var queue = [] | |
queue.push(start) | |
maze[start[0]][start[1]] = '2' | |
while(queue.length > 0){ | |
var size = queue.length | |
result++ | |
for(var i = 0; i < size; i++){ | |
var node = queue.shift() | |
if(node[0] === end[0] && node[1] === end[1]) return result | |
if(walkable(maze, node[0] + 1, node[1])) queue.push([node[0] + 1, node[1]]) | |
if(walkable(maze, node[0] - 1, node[1])) queue.push([node[0] - 1, node[1]]) | |
if(walkable(maze, node[0], node[1] + 1)) queue.push([node[0], node[1] + 1]) | |
if(walkable(maze, node[0], node[1] - 1)) queue.push([node[0], node[1] - 1]) | |
} | |
} | |
return result | |
} | |
function walkable(maze, x, y){ | |
if (maze[x] === undefined || maze[x][y] === undefined) return false //out of bounce | |
if (maze[x][y] === 1) return false //unwalkable | |
if (maze[x][y] === 2) return false //visited | |
maze[x][y] = 2 | |
return true | |
} | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment