let's get IT with DAVINA ๐Ÿ’ป

์ž๋ฃŒ๊ตฌ์กฐ/๊ทธ๋ž˜ํ”„/BFS ๋ณธ๋ฌธ

DEV_IN/Algorithm

์ž๋ฃŒ๊ตฌ์กฐ/๊ทธ๋ž˜ํ”„/BFS

๋‹ค๋นˆ์น˜์ฝ”๋“œ๐Ÿ’Ž 2023. 3. 21. 14:21

BFS(Breadth First Search)

๋‹ค์ฐจ์› ๋ฐฐ์—ด์—์„œ ๊ฐ ์นธ์„ ๋ฐฉ๋ฌธํ•  ๋•Œ ๋„ˆ๋น„๋ฅผ ์šฐ์„ ์œผ๋กœ ๋ฐฉ๋ฌธํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

1. ์‹œ์ž‘ํ•˜๋Š” ์นธ์„ ํ์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋Š” ํ‘œ์‹œ๋ฅผ ๋‚จ๊น€
2. ํ์—์„œ ์›์†Œ๋ฅผ ๊บผ๋‚ด์–ด ๊ทธ ์นธ์— ์ƒํ•˜์ขŒ์šฐ๋กœ ์ธ์ ‘ํ•œ ์นธ์— ๋Œ€ํ•ด 3๋ฒˆ์„ ์ง„ํ–‰
3. ํ•ด๋‹น ์นธ์„ ์ด์ „์— ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด ์•„๋ฌด๊ฒƒ๋„ ํ•˜์ง€ ์•Š๊ณ , ์ฒ˜์Œ์œผ๋กœ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋Š” ํ‘œ์‹œ๋ฅผ ๋‚จ๊ธฐ๊ณ  ํ•ด๋‹น ์นธ์„ ํ์— ์‚ฝ์ž…
4. ํ๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ 2๋ฒˆ์„ ๋ฐ˜๋ณต
๋ชจ๋“  ์นธ์ด ํ์— 1๋ฒˆ์”ฉ ๋“ค์–ด๊ฐ€๋ฏ€๋กœ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” ์นธ์ด N๊ฐœ์ผ ๋•Œ O(N)

์ด ๋•Œ, x๊ฐ€ ํ–‰ & y๊ฐ€ ์—ด


๊ตฌํ˜„

const graph = {
  A: ["B", "C"],
  B: ["A", "D"],
  C: ["A", "G", "H", "I"],
  D: ["B", "E", "F"],
  E: ["D"],
  F: ["D"],
  G: ["C"],
  H: ["C"],
  I: ["C", "J"],
  J: ["I"]
};

const BFS = (graph, startNode) => {
  const visited = []; // ํƒ์ƒ‰์„ ๋งˆ์นœ ๋…ธ๋“œ๋“ค
  let willVisit = []; // ํƒ์ƒ‰ํ•ด์•ผํ•  ๋…ธ๋“œ๋“ค

  willVisit.push(startNode); // ๋…ธ๋“œ ํƒ์ƒ‰ ์‹œ์ž‘

  while (willVisit.length !== 0) { // ํƒ์ƒ‰ํ•ด์•ผํ•  ๋…ธ๋“œ๊ฐ€ ๋‚จ์•„์žˆ๋‹ค๋ฉด
    const node = willVisit.shift(); // queue์ด๊ธฐ ๋•Œ๋ฌธ์— ์„ ์ž…์„ ์ถœ, shift()๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
    if (!visited.includes(node)) { // ํ•ด๋‹น ๋…ธ๋“œ๊ฐ€ ํƒ์ƒ‰๋œ ์  ์—†๋‹ค๋ฉด
      visited.push(node); 
      willVisit = [...willVisit, ...graph[node]];
    }
  }
  return visited;
};

console.log(BFS(graph, "A"));
// ["A", "B", "C", "D", "G", "H", "I", "E", "F", "J"]
Comments