-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.php
89 lines (68 loc) · 1.87 KB
/
day12.php
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
include(__DIR__."/_loader.php");
$input = InputHelper::loadFile("datasets/day12.txt");
$elevations = array_flip(str_split("abcdefghijklmnopqrstuvwxyz"));
$map = [];
foreach ($input as $line) $map[] = str_split($line);
$current = [];
$end = "";
$visited = [];
foreach ($map as $y => $xe) {
foreach ($xe as $x => $e) {
if ($e == 'S') {
$current = [$x, $y];
$e = 'a';
} elseif ($e == 'E') {
$end = $x.'_'.$y;
$e = 'z';
}
$map[$y][$x] = strtr($e, $elevations);
}
}
// Part 1
$answer = 0;
$max_attempts = count($map)*count($map[0]);
$answer = moveDirection($current, 0, $map, $end);
echo "Answer #1: ".$answer.PHP_EOL;
// Part 2
foreach ($map as $y => $xe) {
foreach ($xe as $x => $e) {
if ($e == 0) {
$move = moveDirection([$x,$y], 0, $map, $end);
if ($move <= 0) $move = 1000000;
$answer = min($answer, $move);
}
}
}
echo "Answer #2: ".$answer.PHP_EOL;
function moveDirection($current, $nb, $map, $end) {
global $max_attempts;
if ($nb >= $max_attempts) return -1;
global $visited;
$key = $current[0]."_".$current[1];
if ($key == $end) {
$max_attempts = $nb;
return $nb;
}
if (isset($visited[$key]) && $visited[$key] <= $nb) return -1;
$visited[$key] = $nb;
$vectors = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
$min = 1000000;
$max = $map[$current[1]][$current[0]] + 1;
foreach ($vectors as $vector) {
$next = [
$current[0] + $vector[0],
$current[1] + $vector[1]
];
if (($map[$next[1]][$next[0]] ?? 1000) > $max) continue;
$move = moveDirection($next, ($nb+1), $map, $end);
if ($move > 0) $min = min($min, $move);
}
if ($min == 1000000) return -1000;
return $min;
}