From 792eb4e4f84515afe5c1b5c5292193fa274b83e4 Mon Sep 17 00:00:00 2001 From: beurmuz Date: Mon, 28 Nov 2022 23:01:17 +0900 Subject: [PATCH] #9 22.11.28 > dfs --- src/inf/dfs,bfs/5_rere.js | 22 +++++++++++++++++ src/inf/dfs,bfs/7_1_rerere.js | 46 +++++++++++++++++++++++++++++++++++ src/inf/dfs,bfs/README.md | 2 +- 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/inf/dfs,bfs/5_rere.js create mode 100644 src/inf/dfs,bfs/7_1_rerere.js diff --git a/src/inf/dfs,bfs/5_rere.js b/src/inf/dfs,bfs/5_rere.js new file mode 100644 index 00000000..35809313 --- /dev/null +++ b/src/inf/dfs,bfs/5_rere.js @@ -0,0 +1,22 @@ +"use strict"; + +function solution() { + let answer = []; + let queue = []; + queue.push(1); // 루트 노드 먼저 넣어놓고 시작하기 + + while (queue.length) { + let v = queue.shift(); // 맨 앞 노드 하나 빼기 (빼는 순간 방문했다고 침) + answer.push(v); + + for (let nextVertex of [v * 2, v * 2 + 1]) { + if (nextVertex > 7) continue; // 7보다 크면 건너뜀 + queue.push(nextVertex); // v의 자식 노드들(v*2, v*2+1)을 queue에 넣어줌 + } + } + return answer; +} + +console.log(solution()); + +// 주로 상태트리 문제 (ex. 출발에서 도착지점으로 갈 때의 최단 거리를 구해라) diff --git a/src/inf/dfs,bfs/7_1_rerere.js b/src/inf/dfs,bfs/7_1_rerere.js new file mode 100644 index 00000000..0a30a0bc --- /dev/null +++ b/src/inf/dfs,bfs/7_1_rerere.js @@ -0,0 +1,46 @@ +"use strict"; + +function solution(n, board) { + let answer = 0; + let dx = [-1, -1, 0, 1, 1, 1, 0, -1]; + let dy = [0, 1, 1, 1, 0, -1, -1, -1]; + + function dfs(x, y) { + board[x][y] = 0; + + for (let k = 0; k < 8; k++) { + let nx = x + dx[k]; + let ny = y + dy[k]; + + if (nx >= 0 && nx < n && ny >= 0 && ny < n && board[nx][ny] === 1) { + console.log(nx, ny); + dfs(nx, ny); + } + } + } + + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (board[i][j] === 1) { + answer++; + console.log(i, j); + dfs(i, j); + console.log("dfs end"); + } + } + } + + return answer; +} + +let arr = [ + [1, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 0, 1, 1, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 1, 1], + [1, 1, 0, 1, 1, 0, 0], + [1, 0, 0, 0, 1, 0, 0], + [1, 0, 1, 0, 1, 0, 0], +]; + +console.log(solution(7, arr)); diff --git a/src/inf/dfs,bfs/README.md b/src/inf/dfs,bfs/README.md index 4ea8c052..42096f67 100644 --- a/src/inf/dfs,bfs/README.md +++ b/src/inf/dfs,bfs/README.md @@ -17,7 +17,7 @@ | 2 | X | 22.11.28😢 | | 3 | X | 22.11.28 | | 4 | X | 22.11.28😢 | -| 5 | X | O | +| 5 | X | 22.11.28😢 | | 6 | X | O | | 7-1 | △ | 22.11.28 | | 7-2 | △ | O |