Skip to content

Commit 60a9609

Browse files
author
Jegors Čemisovs
authored
Merge pull request #10 from rabestro/release/4
refactor code
2 parents 5fb5d09 + 9c11bcc commit 60a9609

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

maze-runner.awk

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,39 @@ $NF == "⇨" {
2323
EndRow = Height
2424
}
2525
{
26-
for (;NF;--NF) Grid[Height, NF] = $NF
26+
for (; NF; --NF) Grid[Height, NF] = $NF
2727
}
2828

2929
END {
30-
if (find_path(StartRow, 2)) {
31-
print_maze()
32-
} else {
33-
print "Path not found"
34-
}
30+
if (!find_path(StartRow, 2))
31+
die("Path not found")
32+
print_maze()
3533
}
3634

3735
function find_path(row, col) {
38-
if (row < 1 || row > Height || col < 1 || col > Width || Grid[row, col] != " ") return 0
36+
if (is_not_free(row, col)) return 0
3937
Grid[row, col] = ""
40-
if (row == EndRow && col == Width - 1 \
41-
|| find_path(row + 1, col) || find_path(row - 1, col) \
42-
|| find_path(row, col + 1) || find_path(row, col -1)) return 1
38+
if (is_path_valid(row, col)) return 1
4339
Grid[row, col] = " "
4440
return 0
4541
}
46-
42+
function is_not_free(row, col) {
43+
return row < 1 || row > Height \
44+
|| col < 1 || col > Width \
45+
|| Grid[row, col] != " "
46+
}
47+
function is_path_valid(row, col) {
48+
return row == EndRow && col == Width - 1 \
49+
|| find_path(row + 1, col) \
50+
|| find_path(row - 1, col) \
51+
|| find_path(row, col + 1) \
52+
|| find_path(row, col - 1)
53+
}
4754
function print_maze( row, col) {
4855
while (row++ < Height) {
4956
for (col = Width; col; --col)
5057
$col = Grid[row, col]
5158
print
5259
}
5360
}
61+
function die(message) {print message > "/dev/stderr"; exit 1}

0 commit comments

Comments
 (0)