PHP前端开发

数独验证函数中的错误:为什么验证对角线元素是错误的?

百变鹏仔 5天前 #Python
文章标签 错误

验证数独的函数中存在问题

class solution(object):    def verify_line(self, board, x, y):        for i in range(9):            if board[i][y] == board[x][y] and i != x:                return false            if board[x][i] == board[x][y] and i != y:                return false        # 错误验证        if x == y or x + y == 8:            for k in range(9):                if board[k][k] == board[x][y] and k != x:                    return false                if board[k][8 - k] == board[x][y] and k != x and k - 8 != x:                    return false        return true

问题出在这个错误的验证中:

        if x == y or x + y == 8:            for k in range(9):                if board[k][k] == board[x][y] and k != x:                    return false                if board[k][8 - k] == board[x][y] and k != x and k - 8 != x:                    return false

这段代码尝试验证对角线元素,但它违背了问题要求:

以下是如何更正该函数:

class Solution(object):    def verify_line(self, board, x, y):        for i in range(9):            if board[i][y] == board[x][y] and i != x:                return False            if board[x][i] == board[x][y] and i != y:                return False        return True