LeetCode/go/most-stones-removed-with-same-row-or-column.go

44 lines
653 B
Go
Raw Normal View History

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
}