public class Solution
{
public int[][] FindFarmland(int[][] land)
{
int rows = land.Length;
int cols = land[0].Length;
HashSet<(int, int)> visited = new();
List<int[]> result = new();
int[][] dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (land[row][col] == 1 && !visited.Contains((row, col)))
{
int[] bounds = Dfs(land, visited, row, col, dirs);
result.Add(bounds);
}
}
}
return result.ToArray();
}
private int[] Dfs(int[][] land, HashSet<(int, int)> visited, int row, int col, int[][] dirs)
{
Stack<(int, int)> st = new();
st.Push((row, col));
visited.Add((row, col));
int minRow = row;
int minCol = col;
int maxRow = row;
int maxCol = col;
while (st.Count > 0)
{
var (r, c) = st.Pop();
for (int i = 0; i < dirs.Length; i++)
{
int dr = r + dirs[i][0];
int dc = c + dirs[i][1];
if (0 <= dr && dr < land.Length && 0 <= dc && dc < land[0].Length
&& land[dr][dc] == 1 && !visited.Contains((dr, dc)))
{
visited.Add((dr, dc));
st.Push((dr, dc));
minRow = Math.Min(minRow, dr);
minCol = Math.Min(minCol, dc);
maxRow = Math.Max(maxRow, dr);
maxCol = Math.Max(maxCol, dc);
}
}
}
return [minRow, minCol, maxRow, maxCol];
}
}