-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze-runner.awk
executable file
·64 lines (60 loc) · 1.26 KB
/
maze-runner.awk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env gawk -f
#
# Copyright (c) 2023 Jegors Čemisovs
# License: MIT License
# Repository: https://github.com/rabestro/awk-maze-generator
#
BEGIN {
FPAT = "."
OFS = ""
PathMark = "⋅"
EmptyCell = " "
}
NR == 1 {
Width = NF
}
{
++Height
}
$1 == "⇨" {
StartRow = Height
StartCol = 2
}
$NF == "⇨" {
EndRow = Height
EndCol = Width - 1
}
{
for (; NF; --NF) Grid[Height, NF] = $NF
}
END {
if (!find_path(StartRow, StartCol))
die("Path not found")
print_maze()
}
function find_path(row, col) {
if (is_not_free(row, col)) return 0
Grid[row, col] = PathMark
if (is_path_valid(row, col)) return 1
Grid[row, col] = " "
return 0
}
function is_not_free(row, col) {
return row < 1 || row > Height || col < 1 || col > Width ||
Grid[row, col] != EmptyCell
}
function is_path_valid(row, col) {
return row == EndRow && col == EndCol ||
find_path(row + 1, col) ||
find_path(row - 1, col) ||
find_path(row, col + 1) ||
find_path(row, col - 1)
}
function print_maze( row, col) {
while (row++ < Height) {
for (col = Width; col; --col)
$col = Grid[row, col]
print
}
}
function die(message) {print message > "/dev/stderr"; exit 1}