forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIslandPerimeter.java
66 lines (52 loc) · 1.51 KB
/
IslandPerimeter.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Solution 1
class Solution {
public int islandPerimeter(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j] == 1){
return dfs(grid, i, j, visited);
}
}
}
return 0;
}
private int dfs(int[][] grid, int i, int j, boolean[][] visited){
if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j] == 0){
return 1;
}
if(visited[i][j]){
return 0;
}
visited[i][j] = true;
return dfs(grid, i-1,j, visited) + dfs(grid, i+1,j, visited) + dfs(grid, i,j-1, visited) + dfs(grid, i,j+1, visited);
}
}
// Solution 2
class Solution {
// At every point count the no of surrounding zeros
public int islandPerimeter(int[][] grid) {
int m = grid.length;
if(m<=0){
return 0;
}
int n= grid[0].length;
if(n<=0){
return 0;
}
int count =0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++) {
if(grid[i][j]==1){
if(i==0 || grid[i-1][j]==0) count++;
if(j==0 || grid[i][j-1]==0) count++;
if(i+1==m || grid[i+1][j]==0) count++;
if(j+1==n || grid[i][j+1]==0) count++;
}
}
}
return count;
}
}