Simple DFS solution


  • 0
    G

    Just variant question to leetcode- 200;
    Use simple DFS solution and int[] to count area.

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int res = 0;
            if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 1) {
                        int[] count = new int[1];
                        dfs(grid, count, i, j);
                        res = Math.max(res, count[0]);
                    }
                }
            }
            return res;
        }
        
        private void dfs(int[][] grid, int[] count, int x, int y) {
            if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) return;
            grid[x][y] = 0;
            count[0]++;
            dfs(grid, count, x - 1, y);
            dfs(grid, count, x + 1, y);
            dfs(grid, count, x, y - 1);
            dfs(grid, count, x, y + 1);
            
        }
    }
    

Log in to reply
 

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