-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathProblem_1_Number_Of_Islands.java
35 lines (29 loc) · 1.01 KB
/
Problem_1_Number_Of_Islands.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package Island_Matrix_Traversal;
// Problem Statement: Number of Islands (easy)
// LeetCode Question: 200. Number of Islands
public class Problem_1_Number_Of_Islands {
// Depth First Approach
public int countIslands(int[][] matrix){
int rows = matrix.length;
int cols = matrix[0].length;
int totalIslands = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 1) {
totalIslands++;
visitIslandDFS(matrix, i, j);
}
}
}
return totalIslands;
}
private static void visitIslandDFS(int[][] matrix, int x, int y){
if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length) return;
if (matrix[x][y] == 0) return;
matrix[x][y] = 0;
visitIslandDFS(matrix, x + 1, y);
visitIslandDFS(matrix, x - 1, y);
visitIslandDFS(matrix, x, y + 1);
visitIslandDFS(matrix, x, y - 1);
}
}