DEV Community

Karleb
Karleb

Posted on

#1992. Find All Groups of Farmland

https://leetcode.com/problems/find-all-groups-of-farmland/submissions/1236977483/?envType=daily-question&envId=2024-04-20


/**
 * @param {number[][]} land
 * @return {number[][]}
 */
var findFarmland = function(land) {
    let m = land.length;
    let n = land[0].length;
    let visited = new Array(m);
    for(let i = 0; i < m; i++)
        visited[i] = new Array(n).fill(false);
    let start = [];
    let end = [];
    function dfs(i,j){
        if(i < 0 || i === m || j < 0 || j === n)
            return;
        if(visited[i][j] === true || land[i][j] === 0)
            return;
        if(end[0] + end[1] < i + j)
            end = [i,j];
        visited[i][j] = true;
        dfs(i+1,j);
        dfs(i,j+1);
    }
    let ans = [];
    for(let i = 0; i < m; i++){
        for(let j = 0; j < n; j++){
            if(visited[i][j] === false && land[i][j] === 1){
                start = [i,j];
                end = [i,j];
                dfs(i,j);
                ans.push([...start,...end]);
            }
        }
    }
    return ans;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)