Unable to load image

Day 12

Post code, nerds.

14
Jump in the discussion.

No email address required.


const grd: string[][] 
  = fs.readFileSync(process.argv[2], 'utf-8').split('\n').map(l => l.split(''));
const hgt: number[][]
  = grd.map(r => r.map(ch => (ch==='S' ? 'a' : ch==='E' ? 'z' : ch).charCodeAt(0)));
const dst: number[][] 
  = grd.map(r => r.map(() => 0));

type Cell = {r: number, c: number};
let next: Cell[] = [];
let cur: Cell[] = [];
let step = 0;

// find start setup
grd.forEach((row, r) => {
  const c = row.findIndex(ch => ch==='E')
  if (c !== -1) next = [{r:r, c:c}];
})
hgt[next[0].r][next[0].c] = 'z'.charCodeAt(0);
dst[next[0].r][next[0].c] = -1;

// bfs
while (next.length) {
  step++; cur = next; next = [];
  for (let cell of cur) {
    [ [cell.r-1,cell.c],
      [cell.r+1,cell.c],
      [cell.r,cell.c-1],
      [cell.r,cell.c+1]
    ].forEach(([r,c]) => {
      // out of bounds
      if (r < 0 || grd.length-1 < r
        || c < 0 || grd[r].length-1 < c) return;
      // already visited || too big diff in height
      if (dst[r][c] 
        || hgt[cell.r][cell.c] - hgt[r][c] > 1 ) return;
      // push to next
      dst[r][c] = step;
      next.push({r,c});
    })
  }
};

grd.forEach((row, r) => {
  const c = row.findIndex(ch => ch==='S')
  if (c !== -1) console.log(dst[r][c]);
})
console.log(
  dst.flatMap((row, r) => row.filter((d, c) => d && grd[r][c] === 'a')).sort((a,b) => a-b)[0]
)
Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.