-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-7 Island Perimeter
53 lines (41 loc) · 1.46 KB
/
Day-7 Island Perimeter
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
public class Solution {
public int islandPerimeter(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int up, down, left, right;
int result = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 1) {
if (r == 0) { up = 0; }
else { up = grid[r-1][c]; }
if (c == 0) { left = 0; }
else { left = grid[r][c-1]; }
if (r == rows-1) { down = 0; }
else { down = grid[r+1][c]; }
if (c == cols-1) { right = 0; }
else { right = grid[r][c+1]; }
result += 4-(up+left+right+down);
}
}
}
return result;
}
}
class Solution {
public int islandPerimeter(int[][] grid) {
int m=grid.length;
int n=grid[0].length;
int count=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
count+=4;
if(i>0 && grid[i-1][j]==1) count-=2;
if(j>0 && grid[i][j-1]==1) count-=2;
}
}
}
return count;
}
}