请数独解出对角线约束 EN
最编程
2024-06-01 16:10:13
...
// m[] = input matrix
// (X, R) = local variables to store the position of an empty cell
// (more specifically: the last empty cell of the grid)
f = (m, X, R) =>
// for each row r[] at position y in m[]
// using q as an object for bit-mask storage
m.every(q = (r, y) =>
// for each value v at position x in r[]
r.every((v, x) =>
// is this cell empty?
v ?
// it's not: make sure its value is valid
// g is a helper function testing whether q[k] is modified
// when its v-th bit it set; if not, it means that we have
// twice the same digit on a diagonal or a square
(
g = k => q[k] ^ (q[k] |= 1 << v)
)(
// invoke g for the current anti-diagonal,
// with k in [-8..8]
x - y
) *
g(
// invoke g for the current diagonal,
// with k in [9..25]
x + y + 9
) *
g(
// invoke g for the current square,
// with k in [32..42]
x / 3 | y / 3 + 8 << 2
)
:
// this cell is empty: save its position in (X, R)
// NB: this is guaranteed to be truthy (having empty
// cells does not invalidate the grid)
(X = x, R = r)
)
) ?
// the grid is valid so far
R ?
// there's an empty cell: attempt to set it to 1 .. 9 and
// do recursive calls to see if it leads to a solution
m.some(_ => f(m, R[X]++)) ?
// if successful, return m[]
m
:
// otherwise, reset the cell to 0 afterwards and abort
R[X] = 0
:
// the grid is valid and there's no empty cell: return m[]
m
:
// the grid is invalid: abort right away
0