|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Queue; |
| 5 | + |
3 | 6 | public class _463 {
|
4 | 7 |
|
5 | 8 | public static class Solution1 {
|
@@ -27,4 +30,46 @@ public int islandPerimeter(int[][] grid) {
|
27 | 30 | return count;
|
28 | 31 | }
|
29 | 32 | }
|
| 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 | + } |
30 | 75 | }
|
0 commit comments