|
| 1 | +/** |
| 2 | + * <a href="https://leetcode.com/problems/number-of-islands/">week07-3. number-of-islands</a> |
| 3 | + * <li>Description: return the number of islands is surrounded by water("0") </li> |
| 4 | + * <li>Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix </li> |
| 5 | + * <li>Time Complexity: O(M×N), Runtime 5ms </li> |
| 6 | + * <li>Space Complexity: O(M×N), Memory 52.11MB </li> |
| 7 | + */ |
| 8 | +class Solution { |
| 9 | + private char[][] grid; |
| 10 | + private int m; |
| 11 | + private int n; |
| 12 | + private boolean[][] visit; |
| 13 | + private int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 14 | + |
| 15 | + public int numIslands(char[][] grid) { |
| 16 | + this.grid = grid; |
| 17 | + this.m = grid.length; |
| 18 | + this.n = grid[0].length; |
| 19 | + this.visit = new boolean[m][n]; |
| 20 | + |
| 21 | + int num = 0; |
| 22 | + for (int r = 0; r < m; r++) { |
| 23 | + for (int c = 0; c < n; c++) { |
| 24 | + if (grid[r][c] == '1' && !visit[r][c]) { |
| 25 | + findIsland(r, c); |
| 26 | + num++; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return num; |
| 31 | + } |
| 32 | + |
| 33 | + public void findIsland(int r, int c) { |
| 34 | + Queue<int[]> queue = new LinkedList<>(); |
| 35 | + visit[r][c] = true; |
| 36 | + queue.offer(new int[]{r, c}); |
| 37 | + |
| 38 | + while (!queue.isEmpty()) { |
| 39 | + int[] cur = queue.poll(); |
| 40 | + int cr = cur[0]; |
| 41 | + int cc = cur[1]; |
| 42 | + |
| 43 | + for (int[] dir : directions) { |
| 44 | + int nr = cr + dir[0]; |
| 45 | + int nc = cc + dir[1]; |
| 46 | + if (nr < 0 || nr > m - 1 || nc < 0 || nc > n - 1) { |
| 47 | + continue; |
| 48 | + } |
| 49 | + if (grid[nr][nc] == '1' && !visit[nr][nc]) { |
| 50 | + visit[nr][nc] = true; |
| 51 | + queue.offer(new int[]{nr, nc}); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments