From 5aa7a867fc3d3e479326e88f516dd1cc88c5a45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Khoa=20Hu=E1=BB=B3nh=20=28Daniel=29?= Date: Sat, 20 Apr 2024 23:35:00 +0700 Subject: [PATCH] Create main.go --- solution/1992/main.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 solution/1992/main.go diff --git a/solution/1992/main.go b/solution/1992/main.go new file mode 100644 index 0000000..4119950 --- /dev/null +++ b/solution/1992/main.go @@ -0,0 +1,39 @@ +package main + +func findFarmland(land [][]int) [][]int { + m, n := len(land), len(land[0]) + var answer [][]int + + for r := 0; r < m; r++ { + for c := 0; c < n; c++ { + if land[r][c] == 1 { + rMax, cMax := -1, -1 + dfs(land, r, c, &rMax, &cMax) + answer = append(answer, []int{r, c, rMax, cMax}) + } + } + } + + return answer +} + +func dfs(land [][]int, r, c int, rMax, cMax *int) { + if r < 0 || r >= len(land) || c < 0 || c >= len(land[0]) || land[r][c] == 0 { + return + } + + // Mark current cell as visited + land[r][c] = 0 + + // Update rMax and cMax if current cell is more 'bottom-right' + if r > *rMax { + *rMax = r + } + if c > *cMax { + *cMax = c + } + + // Explore the cell to the right (c + 1) and below (r + 1) + dfs(land, r, c+1, rMax, cMax) // Move right + dfs(land, r+1, c, rMax, cMax) // Move down +}