|
| 1 | +public class Geegong { |
| 2 | + |
| 3 | + /** |
| 4 | + * 1. 하나씩 훑어가면서 1이 되는 시점을 찾아 그 시점부터 dfs 로 방향값을 주어 |
| 5 | + * 방문한 곳은 0으로 바꿔버려 다시는 탐색하지 못하도록 막아버림 |
| 6 | + * 모든 방향값을 주면서 0으로 메꾼 후 1을 리턴하고 리턴된 값들을 누적하면 만들어낼 수 있는 섬의 총 갯수가 된다 |
| 7 | + * time complexity : O (m*n*4) => O(m*n) |
| 8 | + * space complexity : O(m*n) // 따로 memoization 을 위한 변수는 없으나 재귀로 인해 콜스택 발생 |
| 9 | + */ |
| 10 | + public static int[][] vectors = {{0,1}, {1,0}, {0,-1}, {-1,0}}; |
| 11 | + public int numIslands(char[][] grid) { |
| 12 | + |
| 13 | + int totalNumberOfIslands = 0; |
| 14 | + |
| 15 | + for (int rowIdx=0; rowIdx < grid.length; rowIdx++) { |
| 16 | + for (int colIdx=0; colIdx < grid[0].length; colIdx++) { |
| 17 | + // 1이 되는 시점부터 섬이 되는지 체크한다. |
| 18 | + if (grid[rowIdx][colIdx] == '1') { |
| 19 | + totalNumberOfIslands += dfs(grid, rowIdx, colIdx); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + return totalNumberOfIslands; |
| 24 | + } |
| 25 | + |
| 26 | + public int dfs(char[][] origin, int rowIdx, int colIdx) { |
| 27 | + if (rowIdx < 0 || colIdx < 0) { |
| 28 | + // 의미 없는 리턴. 단순히 콜스택 이전으로 돌아가기 위해 임의값 리턴 |
| 29 | + return 1; |
| 30 | + } |
| 31 | + |
| 32 | + if (rowIdx >= origin.length || colIdx >= origin[0].length) { |
| 33 | + // 의미 없는 리턴. 단순히 콜스택 이전으로 돌아가기 위해 임의값 리턴 |
| 34 | + return 1; |
| 35 | + } |
| 36 | + |
| 37 | + if (origin[rowIdx][colIdx] == '0') { |
| 38 | + // 의미 없는 리턴. 단순히 콜스택 이전으로 돌아가기 위해 임의값 리턴 |
| 39 | + return 1; |
| 40 | + } |
| 41 | + |
| 42 | + origin[rowIdx][colIdx] = '0'; // 0 으로 셋팅해서 다음 섬을 찾을때 방문하지 못하도록 방어한다. |
| 43 | + |
| 44 | + for (int[] vector : vectors) { |
| 45 | + int moveRow = vector[0]; |
| 46 | + int moveCol = vector[1]; |
| 47 | + |
| 48 | + dfs(origin, rowIdx + moveRow, colIdx + moveCol); |
| 49 | + } |
| 50 | + |
| 51 | + // 섬이 되는 구역을 다 돌았다면 하나의 섬이 하나 된다고 판단이 되므로 1 리턴 |
| 52 | + return 1; |
| 53 | + } |
| 54 | + |
| 55 | +} |
| 56 | + |
0 commit comments