Skip to content

Commit adf269f

Browse files
committed
Leetcode | Find All Groups of Farmland | Java
1 parent 9f99641 commit adf269f

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

leetcode/src/main/java/com/devstromo/medium/p1992/Solution.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,33 @@ public int[][] findFarmland(int[][] land) {
2727
return result.toArray(new int[result.size()][]);
2828
}
2929

30+
public int[][] findFarmlandBest(int[][] land) {
31+
if (land.length == 0 || land[0].length == 0) {
32+
return new int[][]{
33+
{0}
34+
};
35+
}
36+
int row = land.length;
37+
int col = land[0].length;
38+
39+
List<int[]> rectangles = new ArrayList<>();
40+
for (int currRow = 0; currRow < row; ++currRow) {
41+
for (int currCol = 0; currCol < col; ++currCol) {
42+
if (land[currRow][currCol] == 1) {
43+
int x = currRow;
44+
int y = currCol;
45+
for (x = currRow; x < row && land[x][currCol] == 1; ++x) {
46+
for (y = currCol; y < col && land[x][y] == 1; ++y) {
47+
land[x][y] = 0;
48+
}
49+
}
50+
rectangles.add(new int[]{currRow, currCol, x - 1, y - 1});
51+
}
52+
}
53+
}
54+
return rectangles.toArray(new int[rectangles.size()][]);
55+
}
56+
3057
private void dfs(int[][] land, int r, int c, int[] bounds) {
3158
int m = land.length, n = land[0].length;
3259
// Base case: out of bounds or not farmland

leetcode/src/test/java/com/devstromo/medium/p1992/SolutionUnitTest.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,34 @@ void testFindAllGroupsOfFarmland() {
3939
);
4040
}
4141

42+
@Test
43+
@DisplayName("Test Find All Groups of Farmland Best")
44+
void testFindAllGroupsOfFarmlandBest() {
45+
assertArrayEquals(
46+
new int[][]{
47+
{0, 0, 0, 0},
48+
{1, 1, 2, 2},
49+
},
50+
solution.findFarmlandBest(new int[][]{
51+
{1, 0, 0},
52+
{0, 1, 1},
53+
{0, 1, 1}
54+
})
55+
);
56+
assertArrayEquals(
57+
new int[][]{
58+
{0, 0, 1, 1}
59+
},
60+
solution.findFarmlandBest(new int[][]{
61+
{1, 1},
62+
{1, 1}
63+
})
64+
);
65+
assertArrayEquals(
66+
new int[][]{
67+
{0}
68+
},
69+
solution.findFarmlandBest(new int[][]{})
70+
);
71+
}
4272
}

0 commit comments

Comments
 (0)