[Java/C++] Clean Code


  • 3

    Java DFS

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int m = grid.length, n = grid[0].length, maxarea = 0;
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    maxarea = Math.max(maxarea, dfs(i, j, grid));
            return maxarea;
        }
    
        private int dfs(int i, int j, int[][] grid) {
            return (i < 0 || grid.length <= i || j < 0 || grid[0].length <= j || grid[i][j] <= 0) ? 0
                : grid[i][j]-- + dfs(i, j+1, grid) + dfs(i+1, j, grid) + dfs(i, j-1, grid) + dfs(i-1, j, grid);
        }
    }
    

    C++ DFS

    class Solution {
    public:
        int maxAreaOfIsland(vector<vector<int>>& grid) {
            int m = grid.size(), n = grid[0].size(), maxarea = 0;
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    maxarea = max(maxarea, dfs(i, j, grid));
            return maxarea;
        }
    
    private:
        int dfs(int i, int j, vector<vector<int>>& grid) {
            return (i < 0 || grid.size() <= i || j < 0 || grid[0].size() <= j || grid[i][j] <= 0) ? 0
                : grid[i][j]-- + dfs(i, j+1, grid) + dfs(i+1, j, grid) + dfs(i, j-1, grid) + dfs(i-1, j, grid);
        }
    };
    

    C++ Lambda

    class Solution {
    public:
        int maxAreaOfIsland(vector<vector<int>>& grid) {
            int m = grid.size(), n = grid[0].size(), maxarea = 0;
            auto valid = [&](int i, int j) { return 0 <= i && i < m && 0 <= j && j < n && grid[i][j]; };
            std::function<int(int, int)> dfs = [&](int i, int j){ return !valid(i, j) ? 0 : grid[i][j]-- + dfs(i, j+1) + dfs(i+1, j) + dfs(i, j-1) + dfs(i-1, j);};
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    maxarea = max(maxarea, dfs(i, j));
            return maxarea;
        }
    };
    

    This is very similar to https://leetcode.com/problems/number-of-islands
    Number Of Island

    class Solution {
    public:
        int numIslands(vector<vector<char>>& b) {
            if (!b.size() || !b[0].size())  return 0;
            int m = b.size(), n = b[0].size(), islands = 0;
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    islands += dfs(b, i, j) > 0;
            return islands;
        }
    
    private:
        int dfs(vector<vector<char>>& b, int i, int j) {
            return (i >= 0 && i < b.size() && j >= 0 && j < b[0].size() && b[i][j] == '1') ? b[i][j] = 'v', 1 + dfs(b, i - 1, j) + dfs(b, i + 1, j) + dfs(b, i, j - 1) + dfs(b, i, j + 1) : 0;
        }
    };
    

Log in to reply
 

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