Skip to content

Commit b9d92aa

Browse files
add 461
1 parent 9760d73 commit b9d92aa

File tree

1 file changed

+45
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+45
-0
lines changed

src/main/java/com/fishercoder/solutions/_463.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
36
public class _463 {
47

58
public static class Solution1 {
@@ -27,4 +30,46 @@ public int islandPerimeter(int[][] grid) {
2730
return count;
2831
}
2932
}
33+
34+
public static class Solution2 {
35+
/**
36+
* My completely original solution on 10/4/2021:
37+
* Count the number of island neighbors that each island has, then reduce this number from four and add it to the result.
38+
*/
39+
public int islandPerimeter(int[][] grid) {
40+
int perimeter = 0;
41+
int m = grid.length;
42+
int n = grid[0].length;
43+
boolean[][] visited = new boolean[m][n];
44+
int[] directions = new int[]{0, 1, 0, -1, 0};
45+
for (int i = 0; i < m; i++) {
46+
for (int j = 0; j < n; j++) {
47+
if (grid[i][j] == 1) {
48+
Queue<int[]> queue = new LinkedList<>();
49+
queue.offer(new int[]{i, j});
50+
while (!queue.isEmpty()) {
51+
int[] curr = queue.poll();
52+
if (!visited[curr[0]][curr[1]]) {
53+
visited[curr[0]][curr[1]] = true;
54+
int neighborCount = 0;
55+
for (int k = 0; k < directions.length - 1; k++) {
56+
int newX = curr[0] + directions[k];
57+
int newY = curr[1] + directions[k + 1];
58+
if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1) {
59+
neighborCount++;
60+
if (!visited[newX][newY]) {
61+
queue.offer(new int[]{newX, newY});
62+
}
63+
}
64+
}
65+
perimeter += 4 - neighborCount;
66+
}
67+
}
68+
return perimeter;
69+
}
70+
}
71+
}
72+
return perimeter;
73+
}
74+
}
3075
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy