你的问题听起来令人困惑。一方面,您询问如何验证数独位置是否有效,但在示例中,您展示了程序如何帮助找到放置数字的位置(不是检查您的数独,而是采取行动解决一个) .
要检查数独,您只需验证每行/列/正方形中的数字是否有效。这可以通过一组数据结构轻松实现。我不了解android,也没有时间看,所以这里有一个简单的python代码,它接受一个字符串数组并判断数独是否有效:
from collections import Counter
def isValidCounter(cnt):
del cnt[0]
for i in cnt:
if cnt[i] > 1:
return False
return True
def isValid(arr):
M = [[int(i) if i != '.' else 0 for i in line] for line in arr]
# rows
for i in M:
if not isValidCounter(Counter(i)):
return False
# columns
for i in xrange(9):
if not isValidCounter(Counter(M[j][i] for j in xrange(9))):
return False
# squares
squares = [
[M[0][i] for i in xrange(0, 3)] + [M[1][i] for i in xrange(0, 3)] + [M[2][i] for i in xrange(0, 3)],
[M[0][i] for i in xrange(3, 6)] + [M[1][i] for i in xrange(3, 6)] + [M[2][i] for i in xrange(3, 6)],
[M[0][i] for i in xrange(6, 9)] + [M[1][i] for i in xrange(6, 9)] + [M[2][i] for i in xrange(6, 9)],
[M[3][i] for i in xrange(0, 3)] + [M[4][i] for i in xrange(0, 3)] + [M[5][i] for i in xrange(0, 3)],
[M[3][i] for i in xrange(3, 6)] + [M[4][i] for i in xrange(3, 6)] + [M[5][i] for i in xrange(3, 6)],
[M[3][i] for i in xrange(6, 9)] + [M[4][i] for i in xrange(6, 9)] + [M[5][i] for i in xrange(6, 9)],
[M[6][i] for i in xrange(0, 3)] + [M[7][i] for i in xrange(0, 3)] + [M[8][i] for i in xrange(0, 3)],
[M[6][i] for i in xrange(3, 6)] + [M[7][i] for i in xrange(3, 6)] + [M[8][i] for i in xrange(3, 6)],
[M[6][i] for i in xrange(6, 9)] + [M[7][i] for i in xrange(6, 9)] + [M[8][i] for i in xrange(6, 9)]
]
for square in squares:
if not isValidCounter(Counter(square)):
return False
return True
这是这个数组的样子:
[
"53..7....",
"6..195...",
".98....6.",
"8...6...3",
"4..8.3..1",
"7...2...6",
".6....28.",
"...419..5",
"....8..79"
]