Skip to content
Snippets Groups Projects
Verified Commit 67e4c442 authored by Dmytro Bogatov's avatar Dmytro Bogatov :two_hearts:
Browse files

Pretify binary maze.

parent b3b1d17d
Branches
No related tags found
No related merge requests found
......@@ -22,30 +22,27 @@ namespace CodingInterview.HackerRank
/// <returns>a series of movements describing the shortest path from Y to X</returns>
public List<char> Solve((int i, int j) start, char[,] map)
{
// BFS queue
var queue = new Queue<((int i, int j) tile, List<char> path)>();
// start with a starting tile
queue.Enqueue((tile: start, path: new List<char>()));
// done when all reachable tiles are visited, or earlier
while (queue.Count > 0)
{
// get next tile
var (location, path) = queue.Dequeue();
if (
location.i < 0 || location.i == map.GetLength(0) ||
location.j < 0 || location.j == map.GetLength(1) ||
map[location.i, location.j] == '0' ||
map[location.i, location.j] == '2'
)
{
continue;
}
// if it the target tile, we are done
if (map[location.i, location.j] == 'X')
{
return path;
}
// mark visited
map[location.i, location.j] = '2';
// try all possible directions (4 in this case)
foreach (var direction in new (int i, int j, char where)[] {
(0, +1, 'r'),
(0, -1, 'l'),
......@@ -53,15 +50,35 @@ namespace CodingInterview.HackerRank
(-1, 0, 'u')
})
{
// compute next tile
var newLocation = (i: location.i + direction.i, j: location.j + direction.j);
// do not add to queue if our of maze
if (newLocation.i < 0 || newLocation.i == map.GetLength(0) ||
newLocation.j < 0 || newLocation.j == map.GetLength(1)
)
{
continue;
}
// do not add to queue if blockade or visited
if (map[newLocation.i, newLocation.j] == '0' ||
map[newLocation.i, newLocation.j] == '2')
{
continue;
}
// otherwise add the next tile and update its path
var @copy = new List<char>(path);
@copy.Add(direction.where);
queue.Enqueue((
tile: (i: location.i + direction.i, j: location.j + direction.j),
tile: newLocation,
path: @copy
));
}
}
// if target cannot be reached, return empty path
return new List<char>();
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment