2
\$\begingroup\$

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. (LeetCode)

This is my code

int maxAreaOfIsland(vector<vector<int>>& grid) {
    int max_area = 0; 
    int rows = grid.size(); 
    int columns = grid[0].size();
    vector<vector<bool>> visited(rows, vector<bool>(columns,false));

    for(int i=0 ; i < rows ; ++i){
        for(int j=0; j < columns ; ++j){
            max_area = max(max_area, area(i,j,grid,visited));
        }
    }
    return max_area;
}

int area(int row, int col, vector<vector<int>>& grid, vector<vector<bool>>& visited){
    if(row < 0 || row >= grid.size() || col < 0 || col >= grid[row].size() || visited[row][col]==true || grid[row][col] == 0)
        return 0;

    visited[row][col] = true;
    return (1 + area(row-1,col,grid,visited) + area(row,col-1,grid,visited) + area(row+1,col,grid,visited) + area(row,col+1,grid,visited));
}

It was accepted on LeetCode and worked for all test cases. As you can see, the readability of the code is not good, so I am looking for a Code Review:

  1. How can I improve readability in if() construct and return in area function?

  2. Is there a better way to initialize 2D Vector in C++?

  3. Is there a better way to maintain the visited array? I had to pass that array in every function call. If this data member is declared as as a static data member of the class then can its passing in every recursive call be avoided?

\$\endgroup\$
  • \$\begingroup\$ Can you not just store the island in a 1D array, and use count to count the number of 1s? \$\endgroup\$ – 0liveradam8 Aug 18 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.