Skip to content

Instantly share code, notes, and snippets.

@psqq
Created April 4, 2016 11:17
Show Gist options
  • Save psqq/1f9b3eecfd84829b40cbf625b10e5adf to your computer and use it in GitHub Desktop.
Save psqq/1f9b3eecfd84829b40cbf625b10e5adf to your computer and use it in GitHub Desktop.
// https://repl.it/CCAm/2
"use strict";
var map =
`.....
.....
.###.
.....
.....`.split("\n");
var w = map[0].length, h = map.length;
function is_good_coord(x, y) {
return x >= 0 && x < w && y >= 0 && y < h;
}
function is_floor(x, y) {
return map[y][x] == '.';
}
function is_movable(x, y) {
return is_good_coord(x, y) && is_floor(x, y);
}
var dxdy = [[1, 1], [1, 0], [1, -1], [0, 1], [0, -1], [-1, 1], [-1, 0], [-1, -1]];
function bfs (x1, y1) {
var q = [[x1, y1, 0]], used = [], grid = [];
for (var i=0; i<h; i++) {
used[i] = [];
grid[i] = new Array(w);
grid[i].fill(-1);
}
used[y1][x1] = true;
while (q.length > 0) {
var [x, y, d] = q.shift();
grid[y][x] = d;
for (var [dx, dy] of dxdy) {
var tx = x + dx, ty = y + dy;
if (is_movable(tx, ty) && !used[ty][tx]) {
used[ty][tx] = true;
q.push([tx, ty, d+1]);
}
}
}
return grid;
}
console.log(bfs(0, 0));
function lee (x1, y1, x2, y2) {
var grid = bfs(x1, y1);
if (grid[y2][x2] < 0) return;
var [x, y] = [x2, y2], d = grid[y2][x2];
while (d > 0) {
d -= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment