์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜9] ๊ฒฝ๋กœํƒ์ƒ‰ ์ธ์ ‘ํ–‰๋ ฌ (Javascript)

์€์ง„ 2021. 8. 3. 11:52

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜] ๊ฒฝ๋กœํƒ์ƒ‰ ์ธ์ ‘ํ–‰๋ ฌ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

 

โœ๏ธIdea Sketch

2021-06-30

1. 1๋ฒˆ ์ •์ ์—์„œ N๋ฒˆ ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ๋ชจ๋“  ๊ฒฝ๋กœ์˜ ๊ฐ€์ง€ ์ˆ˜

2. DFS ์ข…๋ฃŒ์กฐ๊ฑด

  • v๊ฐ€ 5์ผ ๋•Œ ์ข…๋ฃŒ
if (v === n) return;

3. DFS ๋กœ์ง

  • DFS(v) v๋Š” ์ •์ 
  • for() ๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•ด ์‹œ์ž‘์ ์ด v์ธ ๋ชจ๋“  ๋ฐฐ์—ด ์ˆ˜ํ–‰
for (let x of arr) {
  if (x[0] === v) {
    arr.push(v);
    DFS(x[1]);
    arr.pop();
  }
}

4. 1 -> 2 -> 4 -> 1 ์ฒ˜๋Ÿผ ๊ณ„์† ์ˆœํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ

  • visited ๋ฐฐ์—ด ์ถ”๊ฐ€
  • visited๊ฐ€ false์ธ ๊ฒฝ์šฐ์—๋งŒ DFS ์ˆ˜ํ–‰
  • ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๋งŒ ๋ฐฉ๋ฌธ
let visited = Array.from({ length: n + 1 }, () => false);

4. DFS ๋กœ์ง ์ˆ˜์ •

  • DFS(v)๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋ฐฉ๋ฌธํ‘œ์‹œ, res.pushํ•˜๊ธฐ
function DFS(v) {
  visited[v] = true;
  res.push(v);
}

5. graph ๋งŒ๋“ค๊ธฐ

let graph = Array.from({ length: n + 1 }, () => Array.from({ length: n + 1 }, () => 0));

for (let [a, b] of arr){
  graph[a][b]=1;
}

 

โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-30

let n = 5;
let arr = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 5], [3, 4], [4, 2], [4, 5]];
let visited = Array.from({ length: n + 1 }, () => false);

let res = [];
let cnt = 0;

function DFS(v) {
  visited[v] = true;
  res.push(v);

  if (v === n) {
    cnt++;
    return;
  }

  for (let x of arr) {
    if (v === x[0] && !visited[x[1]]) {
      DFS(x[1]);
      res.pop();
      visited[x[1]] = false;
    }
  }
}

DFS(1);
console.log(cnt);