Skip to content

Instantly share code, notes, and snippets.

@umair-khokhar
Created November 19, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umair-khokhar/8c0f51d5d89a1ea25c6a4d11de9e381c to your computer and use it in GitHub Desktop.
Save umair-khokhar/8c0f51d5d89a1ea25c6a4d11de9e381c to your computer and use it in GitHub Desktop.
function QueueItem(row, col, distance) {
this.row = row;
this.col = col;
this.distance = distance;
}
const minDistance = (grid) => {
let source = new QueueItem(0, 0, 0);
let visited = [];
grid.forEach(item => visited.push([]));
grid.flat().forEach((item, index) => {
const row = Math.floor(index/width);
const col = Math.floor(index % width);
visited[row][col] = false;
if(item === 's') {
source.row = row;
source.col = col;
}
});
let queue = [];
queue.push(source);
visited[source.row][source.col] = true;
while(queue.length !== 0) {
const currentItem = queue.shift();
if(grid[currentItem.row][currentItem.col] == -1) {
return currentItem.distance;
}
// moving up
if (currentItem.row - 1 >= 0 &&
visited[currentItem.row - 1][currentItem.col] == false) {
queue.push(new QueueItem(currentItem.row - 1, currentItem.col, currentItem.distance + 1));
visited[currentItem.row - 1][currentItem.col] = true;
}
// moving down
if (currentItem.row + 1 < height &&
visited[currentItem.row + 1][currentItem.col] == false) {
queue.push(new QueueItem(currentItem.row + 1, currentItem.col, currentItem.distance + 1));
visited[currentItem.row + 1][currentItem.col] = true;
}
// moving left
if (currentItem.col - 1 >= 0 &&
visited[currentItem.row][currentItem.col - 1] == false) {
queue.push(new QueueItem(currentItem.row, currentItem.col - 1, currentItem.distance + 1));
visited[currentItem.row][currentItem.col - 1] = true;
}
// moving right
if (currentItem.col + 1 < width &&
visited[currentItem.row][currentItem.col + 1] == false) {
queue.push(new QueueItem(currentItem.row, currentItem.col + 1, currentItem.distance + 1));
visited[currentItem.row][currentItem.col + 1] = true;
}
}
return -1;
}
const grid = [
['s', 1, 0],
[0, 1, 1],
[1, -1, 1]
]
/*const grid = [
[0, 1, 0, 's'],
[1, 1, 1, 1],
[1, 1, 1, 'd'],
[1, 1, , 1]
];*/
const width = grid[0].length? grid[0].length: 0;
const height = grid.length;
console.log(`Minimum Distance: ${minDistance(grid)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment