Monday, February 15, 2021

[Google Question] Max Area of Island

Problem: Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example:

[[1,1],
 [1,0]],
 
Output is 3. 


Approach: We can simply apply DFS here. Instead of having a separate visited array, we can use the input grid. We can change the value 1 to -1 when we visit a cell. 

We start DFS for each cell which is having value 1. That's all! 


Implementation in C#:

     public int MaxAreaOfIsland(int[][] grid)

   {

        int rows = grid?.Length ?? 0;
        if (rows == 0)
        {
            return 0;
        }
        int cols = grid[0].Length;
        int maxArea = 0;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                if (grid[i][j] == 1)
                {
                    maxArea = Math.Max(maxArea, this.MaxAreaOfIslandDFS(grid, i, j));
                }
            }
        }
        return maxArea;
    }

    private int MaxAreaOfIslandDFS(int[][] grid, int row, int col)
    {
        if (!this.IsValidLandAndUnVisitedCell(grid, row, col))
        {
            return 0;
        }
        grid[row][col] = -1;
        return 1 +
            this.MaxAreaOfIslandDFS(grid, row - 1, col) +
            this.MaxAreaOfIslandDFS(grid, row + 1, col) +
            this.MaxAreaOfIslandDFS(grid, row, col - 1) +
            this.MaxAreaOfIslandDFS(grid, row, col + 1);
    }


    private bool IsValidLandAndUnVisitedCell(int[][] grid, int row, int col)
    {
        return row >= 0 &&
            row < grid.Length &&
            col >= 0 &&
            col < grid[0].Length &&
            grid[row][col] == 1;
    }


Complexity: O(m *n)  where m is number of rows and n is number of columns.

No comments:

Post a Comment