1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/go/most-stones-removed-with-same-row-or-column.go
2024-08-29 22:03:00 +02:00

43 lines
653 B
Go

package main
func removeStones(stones [][]int) int {
n := len(stones)
makeGraph := func() ([][]int, []bool) {
g := make([][]int, n)
for i := range n {
for j := i + 1; j < n; j++ {
if stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1] {
g[i] = append(g[i], j)
g[j] = append(g[j], i)
}
}
}
return g, make([]bool, n)
}
g, visited := makeGraph()
var runDFS func(int)
runDFS = func(u int) {
visited[u] = true
for _, v := range g[u] {
if !visited[v] {
runDFS(v)
}
}
}
components := 0
for i := range n {
if !visited[i] {
runDFS(i)
components++
}
}
return n - components
}