๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿง  ์•Œ๊ณ ๋ฆฌ์ฆ˜/์œ ํ˜•๋ณ„ ๋Œ€ํ‘œ๋ฌธ์ œ

[BFS][๋ฐฑ์ค€] 7576 ํ† ๋งˆํ†  js ํ’€์ด

by megan07 2023. 12. 27.

์šฐ์„  ์‹œ๊ฐ„์ดˆ๊ณผ๋กœ ์ฐพ์•„์˜ค์‹  ๋ถ„!!!
queue๋ฅผ ์ง์ ‘ ๊ตฌํ˜„ํ•˜์ง€ ์•Š๊ณ  ๋ฐฐ์—ด ๋ฉ”์†Œ๋“œ shift ์“ฐ์‹œ๋ฉด ์‹œ๊ฐ„ ์ดˆ๊ณผ๋‚ฉ๋‹ˆ๋‹ค ใ… ใ… 

 

๐Ÿ’ก์ ‘๊ทผ๋ฐฉ๋ฒ•

- ์ตœ์†Œ ์ผ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ
- ์ธ์ ‘ ํ† ๋งˆํ† ๋“ค์ด ๋จผ์ € ์ต๋Š” ๊ฒƒ
-> BFS๋‹ค!! 

1. ์ฐฝ๊ณ  ์•ˆ์— ์ต์–ด ์žˆ๋Š” ํ† ๋งˆํ† ๋“ค์„ ์ฐพ์•„์„œ ํ์— ๋„ฃ๊ณ 
2. ์ต์–ด ์žˆ๋Š” ํ† ๋งˆํ† ์˜ ์ธ์ ‘ ํ† ๋งˆํ† ๋“ค์ด ์ต๋„๋ก BFS๋กœ ํƒ์ƒ‰

 

 

 

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.first = null;
    this.last = null;
    this.size = 0;
  }
  enqueue(val) {
    var newNode = new Node(val);
    if (!this.first) {
      this.first = newNode;
      this.last = newNode;
    } else {
      this.last.next = newNode;
      this.last = newNode;
    }
    return ++this.size;
  }

  dequeue() {
    if (!this.first) return null;

    var temp = this.first;
    if (this.first === this.last) {
      this.last = null;
    }
    this.first = this.first.next;
    this.size--;
    return temp.value;
  }
}

const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';

// ์ž…๋ ฅ๊ฐ’์ด ์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” ์ž…๋ ฅ ๊ฐ’์˜ ๊ธธ์ด(n), n๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ํ•œ ์ค„์— ํ•˜๋‚˜์˜ ์ž…๋ ฅ๊ฐ’์ด ์ฃผ์–ด์งˆ ๋•Œ
const [n, ...input] = require('fs')
  .readFileSync(filePath)
  .toString()
  .trim()
  .split('\n');

function solution(n, m, box) {
  const queue = new Queue();

  let min = 0;
  const dx = [0, 0, 1, -1];
  const dy = [1, -1, 0, 0];

  //์•ˆ ์ต์€ ํ† ๋งˆํ†  ๊ฐœ์ˆ˜
  let allCnt = 0;

  //๋ฐ•์Šค๋ฅผ ๋Œ๋ฉด์„œ ์ต์€ ํ† ๋งˆํ† ๋“ค ์œ„์น˜ ๊ตฌํ•˜๊ธฐ
  //์•ˆ ์ต์€ ํ† ๋งˆํ†  ๊ฐœ์ˆ˜๋„ ์ฒดํฌ
  box.forEach((row, rIdx) => {
    row.forEach((col, cIdx) => {
      if (col === 1) {
        queue.enqueue([rIdx, cIdx, 0]);
      } else if (col === 0) {
        allCnt++;
      }
    });
  });

  //์ต์€ ํ† ๋งˆํ† ๊ฐ€ ์—†์œผ๋ฉด return -1
  if (queue.size === 0) return -1;

  while (queue.size) {
    //r=row idx, c= column idx, cnt=์ง€๊ธˆ ํ† ๋งˆํ† ๊ฐ€ ์ต๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ๋‚ ์งœ
    const [r, c, cnt] = queue.dequeue();

    min = Math.max(cnt, min);

    for (let i = 0; i < 4; i++) {
      if (
        r + dy[i] >= 0 &&
        r + dy[i] < m &&
        c + dx[i] >= 0 &&
        c + dx[i] < n &&
        box[r + dy[i]][c + dx[i]] === 0
      ) {
        //์•ˆ ์ต์€ ํ† ๋งˆํ†  ๊ฐœ์ˆ˜ --;
        //์•ˆ ์ต์€ ํ† ๋งˆํ† ๋Š” ํ์— ๋„ฃ๊ณ  1++;
        allCnt--;
        box[r + dy[i]][c + dx[i]] = 1;
        queue.enqueue([r + dy[i], c + dx[i], cnt + 1]);
      }
    }
  }

  //์•ˆ ์ต์€ ํ† ๋งˆํ† ๊ฐ€ ์—†์„ ๊ฒฝ์šฐ, 
  return allCnt === 0 ? min : -1;
}

const nArr = n.split(' ').map(Number);

const answer = solution(
  nArr[0],
  nArr[1],
  input.map((row) => row.split(' ').map(Number)),
);

console.log(answer);

 

https://www.acmicpc.net/problem/7576