|
| 1 | +/** |
| 2 | + * ์ฌ์ ๊ฐ์ ์ฐพ๊ธฐ - ๊ทธ๋ํ ํ์ ๋ฌธ์ |
| 3 | + * 2์ฐจ์ ๋ฐ์ด๋๋ฆฌ ๊ทธ๋ฆฌ๋, 1์ ์ฌ, 0์ ๋ฌผ |
| 4 | + * ๊ทธ๋ฆฌ๋์ ๋ชจ๋ ๊ฐ์ฅ์๋ฆฌ๋ ๋ฌผ๋ก ๋๋ฌ์ธ์ฌ ์์ |
| 5 | + * |
| 6 | + * ๋ฌธ์ ์ ๊ทผ: BFS(๋๋น ์ฐ์ ํ์) ์ฌ์ฉ |
| 7 | + * 1. ๊ทธ๋ฆฌ๋๋ฅผ ์ํํ๋ฉด์ ๋
(1)์ ๋ฐ๊ฒฌํ๋ฉด BFS๋ก ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋
์ ํ์ |
| 8 | + * 2. BFS ํ์ ์ค์ ๋ฐฉ๋ฌธํ ๋
์ ๋ฐฉ๋ฌธ ๋ฐฐ์ด์ ํ์ |
| 9 | + * 3. BFS ํ์์ด ๋๋๋ฉด ์ฌ์ ๊ฐ์๋ฅผ ์ฆ๊ฐ |
| 10 | + * 4. ๊ทธ๋ฆฌ๋ ์ ์ฒด๋ฅผ ์ํํ๋ฉด์ ์ฌ์ ๊ฐ์๋ฅผ ์ธ๊ธฐ |
| 11 | + * |
| 12 | + * BFS ์ ํ ์ด์ : ์ ์ฝ ์กฐ๊ฑด(๊ทธ๋ฆฌ๋ ํฌ๊ธฐ ์ต๋ 300x300)์ ๊ณ ๋ คํ์ ๋, |
| 13 | + * - ๊ทธ๋ฆฌ๋๊ฐ ์ปค์ง์๋ก DFS๋ ์ฌ๊ท ํธ์ถ๋ก ์ธํ ์คํ ์ค๋ฒํ๋ก์ฐ ์ํ์ด ์์, |
| 14 | + * - BFS๋ ํ๋ฅผ ์ฌ์ฉํ์ฌ ์ด ์ํ์ ํผํ ์ ์์ |
| 15 | + * - ๋ฐฉ๋ฌธ๋ฐฐ์ด์ ๋ง๋ค์ด์ ์๋ณธ๋ฐ์ดํฐ ๋ณด์กด(๋ถ๋ณ์ฑ ์ ์ง) |
| 16 | + * - ๋จ, BFS๋ ํ๋ฅผ ์ฌ์ฉํ๋ฏ๋ก ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋์ด ๋ ๋ง์ ์ ์์ |
| 17 | + * |
| 18 | + * ์๊ฐ ๋ณต์ก๋: O(MรN) (M: ํ์ ๊ฐ์, N: ์ด์ ๊ฐ์) |
| 19 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(MรN) (๋ฐฉ๋ฌธ ๋ฐฐ์ด๊ณผ ํ๋ฅผ ์ฌ์ฉ) |
| 20 | + */ |
| 21 | +/** |
| 22 | + * @param {character[][]} grid |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var numIslands = function (grid) { |
| 26 | + if (!grid || grid.length === 0) { |
| 27 | + return 0; |
| 28 | + } |
| 29 | + |
| 30 | + const rows = grid.length; |
| 31 | + const cols = grid[0].length; |
| 32 | + let islandCount = 0; |
| 33 | + |
| 34 | + // ๋ฐฉ๋ฌธ ๋ฐฐ์ด ์์ฑ |
| 35 | + const visited = Array(rows) |
| 36 | + .fill() |
| 37 | + .map(() => Array(cols).fill(false)); |
| 38 | + |
| 39 | + // ๋ฐฉํฅ ๋ฐฐ์ด (์, ํ, ์ข, ์ฐ) |
| 40 | + const directions = [ |
| 41 | + [-1, 0], |
| 42 | + [1, 0], |
| 43 | + [0, -1], |
| 44 | + [0, 1], |
| 45 | + ]; |
| 46 | + |
| 47 | + function bfs(startRow, startCol) { |
| 48 | + const queue = [[startRow, startCol]]; |
| 49 | + visited[startRow][startCol] = true; // ์์์ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ |
| 50 | + |
| 51 | + while (queue.length > 0) { |
| 52 | + const [row, col] = queue.shift(); |
| 53 | + |
| 54 | + // 4๋ฐฉํฅ ํ์ |
| 55 | + for (const [dr, dc] of directions) { |
| 56 | + const newRow = row + dr; |
| 57 | + const newCol = col + dc; |
| 58 | + |
| 59 | + // ๋ฒ์ ์์์, ๋ฐฉ๋ฌธํ์ง ์์ ๋
('1')์ด๋ฉด ํ์ |
| 60 | + if ( |
| 61 | + newRow >= 0 && |
| 62 | + newRow < rows && |
| 63 | + newCol >= 0 && |
| 64 | + newCol < cols && |
| 65 | + grid[newRow][newCol] === '1' && |
| 66 | + !visited[newRow][newCol] |
| 67 | + ) { |
| 68 | + queue.push([newRow, newCol]); |
| 69 | + visited[newRow][newCol] = true; // ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // ๊ทธ๋ฆฌ๋ ์ ์ฒด ์ํ |
| 76 | + for (let i = 0; i < rows; i++) { |
| 77 | + for (let j = 0; j < cols; j++) { |
| 78 | + // ๋
('1')์ ๋ฐ๊ฒฌํ๊ณ ์์ง ๋ฐฉ๋ฌธํ์ง ์์์ผ๋ฉด BFS ์์ ๋ฐ ์ฌ ์นด์ดํธ ์ฆ๊ฐ |
| 79 | + if (grid[i][j] === '1' && !visited[i][j]) { |
| 80 | + islandCount++; |
| 81 | + bfs(i, j); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return islandCount; |
| 87 | +}; |
0 commit comments