JSFiddle - React, Tailwind, and code Playground
by Sam Fereday
JavaScript
// Start location will be in the following format:
// [distanceFromTop, distanceFromLeft]
var findShortestPath = function(startCoordinates, grid) {
var distanceFromTop = startCoordinates[0];
var distanceFromLeft = startCoordinates[1];
// Each "location" will store its coordinates
// and the shortest path required to arrive there
var location = {
distanceFromTop: distanceFromTop,
distanceFromLeft: distanceFromLeft,
path: [],
status: 'Start'
};
// Initialize the queue with the start location already inside
var queue = [location];
// Loop through the grid searching for the goal
while (queue.length > 0) {
// Take the first location off the queue
var currentLocation = queue.shift();
// Explore North
var newLocation = exploreInDirection(currentLocation, 'North', grid);
if (newLocation.status === 'Goal') {
return newLocation.path;
} else if (newLocation.status === 'Valid') {
queue.push(newLocation);
}
// Explore East
var newLocation = exploreInDirection(currentLocation, 'East', grid);
if (newLocation.status === 'Goal') {
return newLocation.path;
} else if (newLocation.status === 'Valid') {
queue.push(newLocation);
}
// Explore South
var newLocation = exploreInDirection(currentLocation, 'South', grid);
if (newLocation.status === 'Goal') {
return newLocation.path;
} else if (newLocation.status === 'Valid') {
queue.push(newLocation);
}
// Explore West
var newLocation = exploreInDirection(currentLocation, 'West', grid);
if (newLocation.status === 'Goal') {
return newLocation.path;
} else if (newLocation.status === 'Valid') {
queue.push(newLocation);
}
}
// No valid path found
return false;
};
// This function will check a location's status
// (a location is "valid" if it is on the grid, is not an "obstacle",
// and has not yet been visited by our algorithm)
// Returns "Valid",...