|
| 1 | +/** |
| 2 | + input : 2d matrix filled with '1', '0' |
| 3 | + output : number of islands |
| 4 | +
|
| 5 | + 1 indicates land, 0 means water. |
| 6 | + if lands are surrounded by water we call it island |
| 7 | +
|
| 8 | + example |
| 9 | +
|
| 10 | + 1 1 1. >> 3 islands |
| 11 | + 0 0 0 |
| 12 | + 1 0 1 |
| 13 | +
|
| 14 | + 1 1 1 1 0 |
| 15 | + 1 1 0 1 0 >> 1 island |
| 16 | + 0 0 0 0 0 |
| 17 | +
|
| 18 | + constraints: |
| 19 | + 1) m, n range |
| 20 | + [1, 300] |
| 21 | + 2) can we change the input grid cell? |
| 22 | + there is no restriction. |
| 23 | +
|
| 24 | + solution 1) |
| 25 | +
|
| 26 | + ds : array |
| 27 | + algo : bfs + in-place |
| 28 | +
|
| 29 | + read every cell in grid. |
| 30 | + if cell is '1' |
| 31 | + do bfs, change every visiting cell into '2' << if changing input is allowed. |
| 32 | + increase count |
| 33 | +
|
| 34 | + tc : O(mn), visiting each cell exactly once. |
| 35 | + sc : O(mn) for queue |
| 36 | +
|
| 37 | + optimize?? maintain visited matrix, set or something else.. |
| 38 | + if we are allowed to modify given input matrix |
| 39 | + we don't have to maintain visited matrix, but simply change values |
| 40 | + */ |
| 41 | +class Solution { |
| 42 | + public int numIslands(char[][] grid) { |
| 43 | + int m = grid.length, n = grid[0].length; |
| 44 | + int numberOfIslands = 0; |
| 45 | + for(int i = 0; i < m; i++) { |
| 46 | + for(int j = 0; j < n; j++) { |
| 47 | + if(grid[i][j] == '1') { |
| 48 | + bfsHelper(grid, i, j, m, n); |
| 49 | + numberOfIslands++; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return numberOfIslands; |
| 54 | + } |
| 55 | + private static int[][] directions = { |
| 56 | + {1, 0}, {-1, 0}, {0, 1}, {0, -1} |
| 57 | + }; |
| 58 | + |
| 59 | + private void bfsHelper(char[][] grid, int x, int y, int m, int n) { |
| 60 | + Queue<int[]> queue = new LinkedList<>(); |
| 61 | + queue.add(new int[]{x,y}); |
| 62 | + grid[x][y] = '2'; |
| 63 | + while(!queue.isEmpty()) { |
| 64 | + int[] cur = queue.poll(); |
| 65 | + for(int[] direction : directions) { |
| 66 | + int nx = direction[0] + cur[0]; |
| 67 | + int ny = direction[1] + cur[1]; |
| 68 | + if(nx < 0 || nx >= m || ny < 0 || ny >= n || grid[nx][ny] != '1') continue; |
| 69 | + grid[nx][ny] = '2'; |
| 70 | + queue.add(new int[]{nx, ny}); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments