初级算法题:验证数独,对角线检查逻辑错误,如何修正?

初级算法题:验证数独,对角线检查逻辑错误,如何修正?

初级算法题遇到的问题,求大佬帮忙看一下哪里出问题了

问题:

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:
                    return false
        return true

    def verify_sudoku(self, board, x, y):
        for p in range(3):
            for q in range(3):
                if board[x][y] == board[x + p - x % 3][y + q - y % 3]:
                    if p - x % 3 != 0 or q - y % 3 != 0:
                        return false
        return true

    def isvalidsudoku(self, board):
        """
        :type board: list[list[str]]
        :rtype: bool
        """
        for u in range(9):
            for o in range(9):
                if board[u][o] != ".":
                    if not (self.verify_line(board, u, o) and self.verify_sudoku(board, u, o)):
                        return false
        return true

原因:

在 verify_line 函数中,对于对角线检查部分(即 if x == y or x + y == 8 块),存在逻辑错误。

具体地,对角线检查应该是:

  1. 如果 x 为对角线上的元素,则比较 board[x][x] 和 board[x][8 - x];
  2. 否则,比较 board[x][y] 和 board[8 - x][y];

而原始代码中误将 board[k][k] 和 board[k][8 - k] 与 board[x][y] 进行了比较,这会导致错误的判断。

正确代码:

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[8 - k][k] == board[x][y] and k != x:
                    return False # 比较board[x][y]和board[8 - x][y]
        return True

    def verify_sudoku(self, board, x, y):
        for p in range(3):
            for q in range(3):
                if board[x][y] == board[x + p - x % 3][y + q - y % 3]:
                    if p - x % 3 != 0 or q - y % 3 != 0:
                        return False
        return True

    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for u in range(9):
            for o in range(9):
                if board[u][o] != ".":
                    if not (self.verify_line(board, u, o) and self.verify_sudoku(board, u, o)):
                        return False
        return True

以上就是初级算法题:验证数独,对角线检查逻辑错误,如何修正?的详细内容,更多请关注其它相关文章!