433 · Number of Islands - LintCode

# Description

Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Find the number of islands.

# Solution

public class Solution {
    /**
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
    public int numIslands(boolean[][] grid) {
      if (grid == null || grid.length == 0 || grid[0].length == 0){
          return 0;
      }
      boolean[][] isVisited = new boolean[grid.length][grid[0].length];
      int result = 0;
      for (int i = 0; i < grid.length; i++){
           for (int j = 0; j < grid[0].length; j++){
                 if (grid[i][j] && !isVisited[i][j]){
                    result++;
                    bfs(grid, isVisited, i, j);
                }
           }
      }
     return result;
    }
    private void bfs(boolean[][] grid, boolean[][] isVisited, int startx, int endy){
        //direction
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        
        // 記錄 x, y
        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();
        // 入隊列
        qx.offer(startx);
        qy.offer(endy);
        isVisited[startx][endy] = true;
        
        // 隊列不為空,不停的從隊列裡拿出一個點,拓展鄰居節點放到隊列中
        while (!qx.isEmpty()){
            // 從隊列取出一個點
            int curx = qx.poll();
            int cury = qy.poll();
            // 展開
            for (int i = 0; i < 4; i++){
                int nextx = curx + dx[i];
                int nexty = cury + dy[i];
                if (nextx >= 0 && nextx < grid.length &&
                    nexty >= 0 && nexty < grid[0].length &&
                    !isVisited[nextx][nexty] && grid[nextx][nexty]) {
                        qx.offer(nextx);
                        qy.offer(nexty);
                        isVisited[nextx][nexty] = true;
                    }
            }
        }
    }
}```