From da527027e28b1f65fc9df59cec72603e97cb7cf8 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 29 Aug 2024 22:03:00 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB947.=20Most=20Stones=20Remove?= =?UTF-8?q?d=20with=20Same=20Row=20or=20Column=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...-stones-removed-with-same-row-or-column.go | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 go/most-stones-removed-with-same-row-or-column.go diff --git a/go/most-stones-removed-with-same-row-or-column.go b/go/most-stones-removed-with-same-row-or-column.go new file mode 100644 index 0000000..c9584a2 --- /dev/null +++ b/go/most-stones-removed-with-same-row-or-column.go @@ -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 +}