go: add «947. Most Stones Removed with Same Row or Column»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4856bc8f3e
commit
da527027e2
1 changed files with 43 additions and 0 deletions
43
go/most-stones-removed-with-same-row-or-column.go
Normal file
43
go/most-stones-removed-with-same-row-or-column.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue