Number of Islands

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.

BFS

Time Complexity
O(N*M)
Space Complexity
O(max(N,M)) 递归栈空间

思路

遍历整个矩阵,找到符合要求的点,就是gridi == true并且没有被visited过的。为了防止重复遍历,这里visited的点用gridi = false来标记,可以省去空间。遇到后就上下左右遍历找到所有连着的gridi = true。直到找不到为止,就会重新返回主函数中的for循环,此时count++。岛屿的数目其实就是一共进入了几次主函数中的if(gridi == true)。

代码

public int numIslands(boolean[][] grid) {
    // Write your code here
    //corner case 
    if(grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0){
        return 0;
    }
    int rows = grid.length, cols = grid[0].length;
    int count = 0;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(grid[i][j] == true){
                bfs(grid, i, j, rows, cols);
                count++;
            }
        }
    }
    return count;
}

//check if the matrix[i][j] is valid which means if it is 1 and is not visited
private void bfs(boolean[][] grid, int i, int j, int rows, int cols){
    if(i >= 0 && i < rows && j >= 0 && j < cols && grid[i][j] == true){
        //chagne grid[i][j] to 0 as visited
        grid[i][j] = false;
        //check four directions
        //go up
        bfs(grid, i + 1, j, rows, cols);
        //go down
        bfs(grid, i - 1, j, rows, cols);
        //go left
        bfs(grid, i, j - 1, rows, cols);
        //go right
        bfs(grid, i, j + 1, rows, cols);
    }
}

annielulu
5 声望5 粉丝