1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

go: add «947. Most Stones Removed with Same Row or Column»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-29 22:03:00 +02:00
parent 4856bc8f3e
commit da527027e2
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,43 @@
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
}