LeetCode 36. Valid Sudoku(数独Ⅰ)

题目描述:

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
    The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

    LeetCode 36

分析:
    题意:给出一个数独游戏当前局面,判断此时填入的数字是否合法('.'表示空格,未填写)。
    思路:数独游戏在一个9 * 9的界面上进行,判定规则:每一行、每一列、每一个3 * 3小矩阵内(共(9 * 9) / (3 * 3) = 9个小矩阵)的9个数字不重复,即为合法的。我们只需要对三条规则进行验证即可。采用set,判断是否存在重复数字('.'跳过),若存在,则非法;验证完成,不存在重复数字,则合法。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        // rows
		for(int i = 0; i <= 8; i++){
			set<char> s;
			for(int j = 0; j <= 8; j++){
				if(board[i][j] == '.'){
					continue;
				}
				if(s.count(board[i][j])){
					return false;
				}
				else{
					s.insert(board[i][j]);
				}
			}
		}
		// columns
		for(int i = 0; i <= 8; i++){
			set<char> s;
			for(int j = 0; j <= 8; j++){
				if(board[j][i] == '.'){
					continue;
				}
				if(s.count(board[j][i])){
					return false;
				}
				else{
					s.insert(board[j][i]);
				}
			}
		}
		// cubes
		for(int i = 0; i <= 6; i += 3){
			for(int j = 0; j <= 6; j += 3){
				set<char> s;
				for(int k = 0; k <= 2; k++){
					for(int l = 0; l <= 2; l++){
						if(board[i + k][j + l] == '.'){
							continue;
						}
						if(s.count(board[i + k][j + l])){
							return false;
						}
						else{
							s.insert(board[i + k][j + l]);
						}
					}
				}
			}
		}
		return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值