44 lines
767 B
Go
44 lines
767 B
Go
// Package q1536 implements a solution for https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/
|
|
package q1536
|
|
|
|
func minSwaps(grid [][]int) int {
|
|
n := len(grid)
|
|
|
|
zeros := grid[0] // reuse memory
|
|
for i := range grid {
|
|
z := n - 1
|
|
for z >= 0 && grid[i][z] == 0 {
|
|
z--
|
|
}
|
|
zeros[i] = n - z - 1
|
|
}
|
|
|
|
steps := 0
|
|
for row := range n - 1 {
|
|
needZ := n - row - 1
|
|
if zeros[row] >= needZ {
|
|
continue
|
|
}
|
|
|
|
// Find a row with at lease needZ zeros at the end
|
|
found := -1
|
|
for i := row + 1; i < n; i++ {
|
|
if zeros[i] >= needZ {
|
|
found = i
|
|
break
|
|
}
|
|
}
|
|
if found == -1 {
|
|
return -1
|
|
}
|
|
|
|
steps += found - row
|
|
t := zeros[found]
|
|
copy(zeros[row+1:found+1], zeros[row:found])
|
|
zeros[row] = t
|
|
}
|
|
|
|
return steps
|
|
}
|
|
|
|
var _ = minSwaps
|