|
| 1 | +/** |
| 2 | + * 1992. Find All Groups of Farmland |
| 3 | + * https://leetcode.com/problems/find-all-groups-of-farmland/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested |
| 7 | + * land and a 1 represents a hectare of farmland. |
| 8 | + * |
| 9 | + * To keep the land organized, there are designated rectangular areas of hectares that consist |
| 10 | + * entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, |
| 11 | + * meaning farmland in one group is not four-directionally adjacent to another farmland in a |
| 12 | + * different group. |
| 13 | + * |
| 14 | + * land can be represented by a coordinate system where the top left corner of land is (0, 0) |
| 15 | + * and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and |
| 16 | + * bottom right corner of each group of farmland. A group of farmland with a top left corner |
| 17 | + * at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length |
| 18 | + * array [r1, c1, r2, c2]. |
| 19 | + * |
| 20 | + * Return a 2D array containing the 4-length arrays described above for each group of farmland |
| 21 | + * in land. If there are no groups of farmland, return an empty array. You may return the answer |
| 22 | + * in any order. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number[][]} land |
| 27 | + * @return {number[][]} |
| 28 | + */ |
| 29 | +var findFarmland = function(land) { |
| 30 | + const m = land.length; |
| 31 | + const n = land[0].length; |
| 32 | + const result = []; |
| 33 | + |
| 34 | + for (let r = 0; r < m; r++) { |
| 35 | + for (let c = 0; c < n; c++) { |
| 36 | + if (land[r][c] === 1) { |
| 37 | + let r2 = r; |
| 38 | + let c2 = c; |
| 39 | + |
| 40 | + while (r2 + 1 < m && land[r2 + 1][c] === 1) r2++; |
| 41 | + while (c2 + 1 < n && land[r][c2 + 1] === 1) c2++; |
| 42 | + |
| 43 | + result.push([r, c, r2, c2]); |
| 44 | + |
| 45 | + for (let i = r; i <= r2; i++) { |
| 46 | + for (let j = c; j <= c2; j++) { |
| 47 | + land[i][j] = 0; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | +}; |
0 commit comments