数独 和 “旋转图像”

1、判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

上图是一个部分填充的有效的数独。

数独部分空格内已填入了数字,空白格用 '.' 表示。

class Solution:
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        return self.JudgeRow(board) and self.JudgeCol(board) and self.JudgeBlocks(board)
    #判断每一行是否有重复数字
    def JudgeRow(self,board):
        for i in board:
            temp = []
            board_row = i
            for j in board_row:
                if j != '.':
                    temp.append(j)

            if len(temp) != len(set(temp)):
                return False
        return True
    #判断每一列是否有重复数字
    def JudgeCol(self,board):
        board[:] = zip(*board[::-1])
        for i in board:
            temp = []
            board_col = i
            for j in board_col:
                if j != '.':
                    temp.append(j)

            if len(temp) != len(set(temp)):
                return False
        return True
    #判断3*3是否有重复数字
    def JudgeBlocks(self,board):
        for i in [0,3,6]:
            for j in [0,3,6]:
                temp = []
                for x in [0,1,2]:
                    if board[i+0][j+x] != '.':
                        temp.append(board[i+0][j+x])
                    if board[i+1][j+x] != '.':
                        temp.append(board[i+1][j+x])
                    if board[i+2][j+x] != '.':
                        temp.append(board[i+2][j+x])

                if len(temp) != len(set(temp)):
                    return False
        return True

2、给定一个 × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
class Solution:
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        matrix.reverse()
        for i in range(len(matrix)-1):
            for j in range(i,len(matrix)):
                if j == i:
                    continue
                else:
                    temp = matrix[i][j]
                    matrix[i][j] = matrix[j][i]
                    matrix[j][i] = temp
原创文章 24 获赞 45 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weilixin88/article/details/86602912