[LeetCode] 036. Valid Sudoku (Easy) (C++)

指数:[LeetCode] Leetcode 解决问题的指数 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


036. Valid Sudoku (Easy)

链接

题目:https://leetcode.com/problems/valid-sudoku/
代码(github):https://github.com/illuz/leetcode

题意

推断一个数独是否有效。
有效的数独不强求有解。

分析

仅仅要同一行、列、块里没有同样数字即可了。


开个数组记录即可了。没什么难度。能够用二进制来表示。表位运算加速。

(注意是推断有效,不是有解,我刚開始给求解了,TLE 了好多次。

。)

代码

C++:

class Solution {
private:
	int row[9], col[9], sqr[3][3];
	bool check(int x, int y, int val) {
		return !((row[x]>>val)&1) && !((col[y]>>val)&1) && !((sqr[x/3][y/3]>>val)&1);
	}
	void mark(int x, int y, int val) {
		row[x] |= (1<<val);
		col[y] |= (1<<val);
		sqr[x/3][y/3] |= (1<<val);
	}<pre name="code" class="java">//	求解 Sudoku
//	void unmark(int x, int y, int val) {
//		row[x] -= (1<<val);
//		col[y] -= (1<<val);
//		sqr[x/3][y/3] -= (1<<val);
//	}
//	bool dfs(int pos, vector<vector<char> > &board) {
//		// x = pos / 9, y = pos % 9
//		if (pos == 81)
//			return true;
//		if (board[pos/9][pos%9] != '.') {
//			return dfs(pos + 1, board);
//		} else {
//			for (int i = 0; i < 9; i++)
//				if (check(pos/9, pos%9, i)) {
//					mark(pos/9, pos%9, i);
//					if (dfs(pos + 1, board))
//						return true;
//					unmark(pos/9, pos%9, i);
//				}
//		}
//		return false;
//	}
public:
    bool isValidSudoku(vector<vector<char> > &board) {
		memset(row, 0, sizeof(row));
		memset(col, 0, sizeof(col));
		memset(sqr, 0, sizeof(sqr));
		for (int i = 0; i < board.size(); i++)
			for (int j = 0; j < board[i].size(); j++)
				if (board[i][j] != '.') {
					if (!check(i, j, board[i][j] - '1'))
						return false;
					mark(i, j, board[i][j] - '1');
				}
		return true;
		// return dfs(0, board);
    }
};




版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4802961.html