Skip to content

Instantly share code, notes, and snippets.

@XIAOLONGLII
Created June 14, 2020 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XIAOLONGLII/ce064f157748b1c804517ce9d5499b8e to your computer and use it in GitHub Desktop.
Save XIAOLONGLII/ce064f157748b1c804517ce9d5499b8e to your computer and use it in GitHub Desktop.
/*
In a 2d matrix, there are islands are surrounded by water.
For easier understand, we use 1 stands for islands, 0 stands for water.
A example would be:
1 0 0 0
1 1 1 0
0 0 1 0
1 0 0 0
There are 2 islands in the matrix.
the first one is:
1
1 1 1
1
The second one is
1 (on the index of( 3, 0)
Find numbers of islands by giving a 2d matrix.
*/
class Island {
public static void main(String[] args) {
int[][] matrix = {{1, 0, 0, 0},
{1, 1, 1, 0},
{0, 0, 1, 0},
{1, 0, 0, 0}};
System.out.println(numOfIslands(matrix));
// here should print 2
int[][] matrix2 = {{1, 0, 0, 0},
{1, 0, 1, 0},
{0, 0, 1, 0},
{1, 0, 0, 0}};
System.out.println(numOfIslands(matrix2));
// here should print 3
}
private int numOfIslands(int[][] matrix) {
int countIslands = 0;
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == 1) {
DFS(matrix, i, j);
countIslands++;
}
}
}
return countIslands;
}
private void DFS(int[][] matrix, int row, int col) {
if(row < 0 || row >= matrix.length || col < 0 || col > matrix[0].length || matrix[row][col] != 1) {
return;
}
matrix[row][col] = 2;
DFS(matrix, row+1, col);
DFS(matrix, row-1, col);
DFS(matrix, row, col+1);
DFS(matrix, row, col-1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment