RosettaCodeData/Task/Maze-solving/D/maze-solving.d

43 lines
1.4 KiB
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.stdio, std.random, std.string, std.array, std.algorithm,
2015-02-20 00:35:01 -05:00
std.file, std.conv;
2013-04-10 21:29:02 -07:00
2013-10-27 22:24:23 +00:00
enum int cx = 4, cy = 2; // Cell size x and y.
enum int cx2 = cx / 2, cy2 = cy / 2;
enum pathSymbol = '.';
2013-04-10 21:29:02 -07:00
struct V2 { int x, y; }
2015-02-20 00:35:01 -05:00
bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc {
2013-04-10 21:29:02 -07:00
if (s == end)
return true;
2015-02-20 00:35:01 -05:00
foreach (immutable d; [V2(0, -cy), V2(+cx, 0), V2(0, +cy), V2(-cx, 0)])
2013-04-10 21:29:02 -07:00
if (maze[s.y + (d.y / 2)][s.x + (d.x / 2)] == ' ' &&
maze[s.y + d.y][s.x + d.x] == ' ') {
2017-09-23 10:01:46 +02:00
//Would this help?
// maze[s.y + (d.y / 2)][s.x + (d.x / 2)] = pathSymbol;
2013-04-10 21:29:02 -07:00
maze[s.y + d.y][s.x + d.x] = pathSymbol;
if (solveMaze(maze, V2(s.x + d.x, s.y + d.y), end))
return true;
maze[s.y + d.y][s.x + d.x] = ' ';
}
return false;
}
void main() {
2015-02-20 00:35:01 -05:00
auto maze = "maze.txt".File.byLine.map!(r => r.chomp.dup).array;
immutable h = (maze.length.signed - 1) / cy;
2013-04-10 21:29:02 -07:00
assert (h > 0);
2015-02-20 00:35:01 -05:00
immutable w = (maze[0].length.signed - 1) / cx;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
immutable start = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h));
immutable end = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h));
2013-04-10 21:29:02 -07:00
maze[start.y][start.x] = pathSymbol;
2013-10-27 22:24:23 +00:00
if (!solveMaze(maze, start, end))
return "No solution path found.".writeln;
maze[start.y][start.x] = 'S';
maze[end.y][end.x] = 'E';
writefln("%-(%s\n%)", maze);
2013-04-10 21:29:02 -07:00
}