πŸ“DFS μŠ€νƒμœΌλ‘œ λ¬Έμ œν’€κΈ°

10_2pangΒ·2023λ…„ 6μ›” 5일
0

βš½οΈνŠΈλŸ¬λΈ”μŠˆνŒ…

λͺ©λ‘ 보기
51/94
post-thumbnail

πŸ‘¨β€πŸ’»Β μ‚¬κ±΄


μ΄λ²ˆμ—λŠ” dfs 완전탐색을 ν†΅ν•˜μ—¬ λ‹€λ₯Έλ¬Έμ œλ₯Ό ν’€μ–΄λ³΄μ•˜λ‹€.

βœ…Β ν•΄κ²°


  • μ½”λ“œ
const graph = {
  0: [1, 2, 4],
  1: [0, 5],
  2: [0, 5],
  3: [4],
  4: [0, 3],
  5: [1, 2],
};
function dfs(graph, start) {
  // λ°©λ¬Έν–ˆλŠ”μ§€ 체크
  const visited = Array(6).fill(false);

  // 처음 μ‹œμž‘ μŠ€νƒ μ„€μ • ( λ°°μ—΄μ˜ 인자의 ꡬ성은 [νƒμƒ‰λ…Έλ“œ,λΆ€λͺ¨λ…Έλ“œ] 둜 ꡬ성)
  const stack = [[start, -1]];

	// λ°©λ¬Έν•œ λ…Έλ“œλ₯Ό μˆœμ„œμ— 맞게 μ •λ ¬
  const result = [];

	// TODO : μŠ€νƒμ— 아무 데이터도 μ—†μ„λ•ŒκΉŒμ§€ νƒμƒ‰ν•˜κΈ°
  while (stack.length) {
		// currentNoda 와 parentNode λ₯Ό μŠ€νƒμ˜ λ°μ΄ν„°κ°’μœΌλ‘œ μ„€μ •
    let [currentNode, parentNode] = stack.pop();

		// μ²˜μŒμ— 이뢀뢄을 μ œμ™Έν•˜κ³  문제λ₯Ό ν’€μ–΄μ„œ λ¬΄ν•œλ£¨ν”„μ— λ“€μ–΄κ°”μŒ,,
    if (visited[currentNode]) {
      continue;
    }

		// 이제 탐색을 ν–ˆμœΌλ‹ˆ, 탐색을 ν–ˆλ‹€κ³  ν‘œμ‹œν•˜κ³  pop을 ν–ˆλ˜κ²ƒ 원볡
    visited[currentNode] = true;
		stack.push([currentNode, parentNode]);

		// λ°©λ¬Έν•œ λ…Έλ“œλ₯Ό νƒμƒ‰μˆœμ„œλŒ€λ‘œ push
    result.push(currentNode);

		// μ„ νƒν•œ λ…Έλ“œμ˜ value 쀑에 νƒμƒ‰ν•˜μ§€ μ•Šμ€ λ…Έλ“œλ“€μ„ μ „λΆ€ μŠ€νƒμ— push ν•œλ‹€.
    for (const node of graph[currentNode]) {
      if (!visited[node]) stack.push([node, currentNode]);
    }

		//이제 더이상 탐색할 λ…Έλ“œκ°€ μ—†λ‹€λ©΄ μ’…λ£Œ.
  }
  return result;
}
console.log(dfs(graph, 0));
  • κ²°κ³Ό
[ 0, 4, 3, 2, 5, 1 ]
profile
μ£Όλ‹ˆμ–΄ ν”„λ‘ νŠΈμ—”λ“œ 개발자 이광렬 μž…λ‹ˆλ‹€ 🌸

0개의 λŒ“κΈ€