算法43--Valid Sudoku

本文介绍了一种有效的算法来验证9x9数独板的有效性,确保每行、每列和每个3x3子网格中的数字1-9不重复。通过检查行、列和子网格的数字分布,算法能快速判断数独是否符合规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.


A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

判断一个数组是否合法,每一行,每一列以及每一个方格只包含一个1--9数字,不能有重复。

检查每一行   检查每一列   检查每一个方格

class Solution:
    def isValidSudoku(self, board):
        #检查行       
        for i in range(0, 9):
            row = [v for v in board[i] if v !='.']
            #print('row',row)
            if len(row)!=len(set(row)):
                return False
        
        #检查列
        for c in range(0, 9):
            col=[]
            for r in range(0, 9):
                if board[r][c]!='.':
                    col.append(board[r][c])            
            #print('row',col)
            if len(col)!=len(set(col)):
                return False
            
        #检查子矩阵
        for r in range(1, 4):
            for c in range(1, 4):
                arr = []
                rs = 3*(r-1)
                re = (3*r-1)
                cs = 3*(c-1)
                ce = (3*c-1)             
                for i in range(rs, re+1):
                    for j in range(cs, ce+1):
                        if board[i][j]!='.':
                            arr.append(board[i][j])
                #print('arr',arr)
                if len(arr)!=len(set(arr)):
                    return False
        return True

看一下大神的解法:

row表示每一行各个数字是否出现   row[3][4]表示第四行数字四出现过

col表示每一列各个数字是否出现

box表示每一个方格,数字是否出现

public static boolean isValidSudoku(char[][] board) {
	boolean[][] row = new boolean[9][9];
	boolean[][] col = new boolean[9][9];
	boolean[][] box = new boolean[9][9];

	for (int i = 0; i < 9; i++) {
		for (int j = 0; j < 9; j++) {
			char c = board[i][j];
			if (c == '.')
				continue;

			if (c < '0' || c > '9')
				return false;

			int number = c - '1';
			if (row[i][number] || col[j][number] || box[(i / 3) * 3 + j / 3][number])
				return false;

			row[i][number] = true;
			col[j][number] = true;
			box[(i / 3) * 3 + j / 3][number] = true;
		}
	}
	return true;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值