go: add «1267. Count Servers that Communicate»

URL:	https://leetcode.com/problems/count-servers-that-communicate/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-23 10:46:31 +01:00
parent 854ec005a6
commit c5653d345f
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,40 @@
package main
const (
NOT_SEEN int = -1
SERVER int = 1
)
func countServers(grid [][]int) int {
count := 0
inCol := make([]int, len(grid[0]))
lastInRow := make([]int, len(grid))
for y, _ := range lastInRow {
lastInRow[y] = NOT_SEEN
}
for y, row := range grid {
countInRow := 0
for x, state := range row {
if state == SERVER {
countInRow++
inCol[x]++
lastInRow[y] = x
}
}
if countInRow > 1 {
count += countInRow
lastInRow[y] = NOT_SEEN
}
}
for y, _ := range grid {
if lastInRow[y] != NOT_SEEN && inCol[lastInRow[y]] > 1 {
count++
}
}
return count
}