Java easy DFS


  • 0
    M
    1. There is only one island in the lake. So we loop first and find the first entry to the island.
    2. use DFS, perimeter will be added only once you reach out of the island, which means reach the water or reach the boundary.
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            for (int i = 0;i<grid.length;i++) {
                for (int j = 0;j<grid[i].length;j++) {
                    if (grid[i][j] == 1) return dfs(grid, i, j);
                }
            }
            return 0;
        }
    
        private int dfs(int[][] grid, int i, int j) {
            if (i<0 || i == grid.length || j<0 || j==grid[0].length) return 1;
            if (grid[i][j] == 0) return 1;
            if (grid[i][j] == -1) return 0;
            grid[i][j] = -1;
            return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.