add new solutions

This commit is contained in:
Yiyang Kang 2026-03-13 16:18:54 +09:00
parent f249852923
commit f297e11859
Signed by: kkyy
SSH key fingerprint: SHA256:lJSbAzC3MvrSORdvIVK6h/3g+rVKJNzM7zq0MgA9WKY
10 changed files with 373 additions and 0 deletions

View file

@ -0,0 +1,44 @@
// 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