|
| 1 | +package matrix; |
| 2 | + |
| 3 | +import annotation.Platform; |
| 4 | +import annotation.Quality; |
| 5 | +import annotation.Site; |
| 6 | +import annotation.Stage; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +/** |
| 10 | + * 463. Island Perimeter |
| 11 | + */ |
| 12 | +@Platform(Site.LEETCODE) |
| 13 | +@Quality(Stage.TESTED) |
| 14 | +public class IslandPerimeter { |
| 15 | + |
| 16 | + public int islandPerimeter(int[][] grid) { |
| 17 | + int[] start = getStartingCell(grid); |
| 18 | + return dfs(grid, new boolean[grid.length][grid[0].length], start[0], start[1]); |
| 19 | + } |
| 20 | + |
| 21 | + private int dfs(int[][] grid, boolean[][] visited, int row, int col) { |
| 22 | + if (!isValid(row, col, grid) || visited[row][col]) |
| 23 | + return 0; |
| 24 | + |
| 25 | + visited[row][col] = true; |
| 26 | + return getPerimeter(grid, row, col) + dfs(grid, visited, row + 1, col) |
| 27 | + + dfs(grid, visited, row - 1, col) |
| 28 | + + dfs(grid, visited, row, col + 1) |
| 29 | + + dfs(grid, visited, row, col - 1); |
| 30 | + } |
| 31 | + |
| 32 | + private int getPerimeter(int[][] grid, int row, int col) { |
| 33 | + int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; |
| 34 | + int perimeter = 0; |
| 35 | + |
| 36 | + for (int[] dir : dirs) { |
| 37 | + int newRow = row + dir[0]; |
| 38 | + int newCol = col + dir[1]; |
| 39 | + if (newRow < 0 || newRow >= grid.length || newCol < 0 || newCol >= grid[0].length || grid[newRow][newCol] == 0) { |
| 40 | + perimeter++; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return perimeter; |
| 45 | + } |
| 46 | + |
| 47 | + private boolean isValid(int row, int col, int[][] grid) { |
| 48 | + return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Gets the fist cell which is part of the island |
| 53 | + * @param grid the island grid |
| 54 | + * */ |
| 55 | + private int[] getStartingCell(final int[][] grid) { |
| 56 | + for (int i = 0; i < grid.length; i++) { |
| 57 | + for (int j = 0; j < grid[0].length; j++) { |
| 58 | + if (grid[i][j] == 1) |
| 59 | + return new int[]{i, j}; |
| 60 | + } |
| 61 | + } |
| 62 | + return new int[]{-1, -1}; |
| 63 | + } |
| 64 | + |
| 65 | + @Test |
| 66 | + public void test() { |
| 67 | + System.out.println(islandPerimeter(new int[][]{{0, 1, 0}, {0, 1, 1}, {0, 1, 0},})); |
| 68 | + } |
| 69 | +} |
0 commit comments