-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path463.java
More file actions
116 lines (97 loc) · 3.29 KB
/
463.java
File metadata and controls
116 lines (97 loc) · 3.29 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
__________________________________________________________________________________________________
sample 5 ms submission
class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int count = 0;
int m = grid.length, n = grid[0].length;
for(int i=0; i<m; i++) {
for(int j=0; j<n; 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;
}
}
__________________________________________________________________________________________________
sample 6 ms submission
class Solution {
public int islandPerimeter(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int result = 0;
for(int i = 0; i < grid.length; i++)
{
for(int j = 0; j < grid[i].length; j++)
{
if(grid[i][j] == 1) {
result += 4;
if(i > 0 && grid[i-1][j] == 1) result -= 2;
if(j > 0 && grid[i][j-1] == 1) result -= 2;
}
}
}
return result;
}
}
__________________________________________________________________________________________________
sample 49436 kb submission
class Solution {
private static class Counter {
int val;
}
public int islandPerimeter(int[][] grid) {
int[] initialPos = new int[2];
loop:
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[i].length; j++) {
if (grid[i][j] == 1) {
initialPos[0] = i;
initialPos[1] = j;
break loop;
}
}
}
Counter counter = new Counter();
count(counter, grid, initialPos);
return counter.val;
}
private void count(Counter counter, int[][] grid, int[] pos) {
if (pos[0] < 0
|| pos[0] == grid.length
|| pos[1] < 0
|| pos[1] == grid[pos[0]].length
|| grid[pos[0]][pos[1]] == 2
|| grid[pos[0]][pos[1]] == 0
) {
return;
}
grid[pos[0]][pos[1]] = 2;
if (pos[0] == 0 || grid[pos[0]-1][pos[1]] == 0) {
counter.val++;
}
if (pos[0] == grid.length - 1 || grid[pos[0]+1][pos[1]] == 0) {
counter.val++;
}
if (pos[1] == 0 || grid[pos[0]][pos[1]-1] == 0) {
counter.val++;
}
if (pos[1] == grid[pos[0]].length - 1 || grid[pos[0]][pos[1]+1] == 0) {
counter.val++;
}
count(counter, grid, new int[]{pos[0]+1, pos[1]});
count(counter, grid, new int[]{pos[0]-1, pos[1]});
count(counter, grid, new int[]{pos[0], pos[1]+1});
count(counter, grid, new int[]{pos[0], pos[1]-1});
}
}