Skip to content

Commit 669006e

Browse files
authored
Create 463. Island Perimeter.java
1 parent 337e5c3 commit 669006e

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// 인접한 1의 개수를 구한다.
2+
// 1 -> 3, 2 -> 2, 3 -> 1, 4 -> 0
3+
4+
class Solution {
5+
static int[] dx = {-1, 1, 0, 0};
6+
static int[] dy = {0, 0, -1, 1};
7+
8+
public int islandPerimeter(int[][] grid) {
9+
int sum = 0;
10+
for (int i = 0; i<grid.length; i++) {
11+
for (int k = 0; k<grid[0].length; k++) {
12+
if (grid[i][k] == 0) continue;
13+
int cnt = adjacentCnt(grid, i, k);
14+
sum += calAdjacent(cnt);
15+
}
16+
}
17+
return sum;
18+
}
19+
20+
int adjacentCnt (int[][] grid, int x, int y) {
21+
int cnt = 0;
22+
23+
for (int i = 0; i<4; i++) {
24+
int nx = x + dx[i];
25+
int ny = y + dy[i];
26+
27+
if (nx < 0 || ny < 0 || nx >= grid.length || ny >= grid[0].length) continue;
28+
if (grid[nx][ny] == 1) cnt++;
29+
}
30+
return cnt;
31+
}
32+
33+
int calAdjacent(int num) {
34+
switch (num) {
35+
case 0:
36+
return 4;
37+
case 1:
38+
return 3;
39+
case 2:
40+
return 2;
41+
case 3:
42+
return 1;
43+
default:
44+
return 0;
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)