LeetCode: Number of Islands

// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

// Example 1:

// 11110
// 11010
// 11000
// 00000
// Answer: 1

// Example 2:

// 11000
// 11000
// 00100
// 00011
// Answer: 3

public class NumberOfIslands {

    public int numIslands(char[][] mat) {
    //base cases
if(mat==null || mat.length<1){
return 0;
}
int count = 0;
for(int i=0;i<mat.length; i++){
for(int j = 0;j<mat[0].length; j++){
if(mat[i][j]=='1'){
count++;
setNeighbors(mat, i, j);
}
}
}
return count;
}

public static void setNeighbors(char[][] mat, int i, int j){
//if we reached outside the matrix or the element is not 1, we don't need to do anything
if(i<0 || j<0 || i>=mat.length || j>=mat[0].length || mat[i][j]!='1'){
return;
}
//reset itself to zero
mat[i][j] = '0';
//reset left neighbor
setNeighbors(mat, i-1, j);
//reset top neighbor
setNeighbors(mat, i, j-1);
//reset right neighbor
setNeighbors(mat, i+1, j);
//reset bottom neighbor
setNeighbors(mat, i, j+1);
}
}

No comments:

Post a Comment