Created
December 12, 2022 12:37
-
-
Save mmirzaee/72e651b40ceeed1015548df7c9737ab3 to your computer and use it in GitHub Desktop.
AoC 2022, part2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const content = fs.readFileSync("input").toString().split("\n").map(i => i.split('')); | |
content.pop(); | |
let routes = []; | |
let starts = []; | |
end = { | |
i: 0, | |
j: 0 | |
}; | |
for (let i = 0; i < content.length; i++) { | |
for (let j = 0; j < content[i].length; j++) { | |
if (content[i][j] == 'S') { | |
content[i][j] = 'a' | |
} | |
if (content[i][j] == 'E') { | |
content[i][j] = 'z' | |
end = { | |
i: i, | |
j: j | |
}; | |
} | |
if (content[i][j] == 'a') { | |
starts.push(i + ':' + j); | |
} | |
let r = [] | |
if (content[i - 1] !== undefined && content[i - 1][j].charCodeAt(0) <= (content[i][j].charCodeAt(0) + 1)) { | |
r.push((i - 1) + ':' + j); | |
} | |
if (content[i][j + 1] !== undefined && content[i][j + 1].charCodeAt(0) <= (content[i][j].charCodeAt(0) + 1)) { | |
r.push(i + ':' + (j + 1)); | |
} | |
if (content[i + 1] !== undefined && content[i + 1][j].charCodeAt(0) <= (content[i][j].charCodeAt(0) + 1)) { | |
r.push((i + 1) + ':' + j); | |
} | |
if (content[i][j - 1] !== undefined && content[i][j - 1].charCodeAt(0) <= (content[i][j].charCodeAt(0) + 1)) { | |
r.push(i + ':' + (j - 1)); | |
} | |
routes[i + ':' + j] = r; | |
} | |
} | |
shortest = 10000; | |
starts.forEach(s => { | |
paths = [ | |
[s] | |
]; | |
r = Object.assign({}, routes); | |
while (paths.length) { | |
item = paths.shift(); | |
let last_item = item.pop() | |
if (end.i == last_item.split(':')[0] && end.j == last_item.split(':')[1]) { | |
if (item.length < shortest) shortest = item.length; | |
} | |
if (r[last_item] !== undefined) { | |
r[last_item].forEach(x => { | |
paths.push([...item, last_item, x]) | |
}) | |
delete r[last_item] | |
} | |
} | |
}); | |
console.log(shortest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment