Simple Concise C++


  • 0
    M

    vector<int> dirX = { -1, 0, 1, 0 };
    vector<int> dirY = { 0, 1, 0, -1 };

    int numIslands(vector<vector<char>>& grid) {
        int m(grid.size()), n(!m ? 0 : grid[0].size()), res(0);
        if (n == 0 || m == 0) return res;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] == '1')
                    fill(grid, m, n, i, j), res++;
        return res;
    
    
    
    void fill(vector<vector<char>>& grid, int& m, int& n, int x, int y){
        for (int i = 0; i < 4; i++){
            int newX(x + dirX[i]), newY(y + dirY[i]);
            if (newX < 0 || newX >= m || newY < 0 || newY >= n ||
                grid[newX][newY] == '0') continue;
            grid[newX][newY] = '0';
            fill(grid, m, n, newX, newY);
        }
    }

Log in to reply
 

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