LeetCode_Valid Sudoku
来源:互联网 发布:淘宝打造爆款教程 编辑:程序博客网 时间:2024/05/28 17:05
一.题目
Valid Sudoku
Total Accepted: 29804 Total Submissions: 109584My SubmissionsDetermine 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 '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Show Tags
Have you met this question in a real interview?
Yes
No
Discuss
二.解题技巧
这道题比较简单,就是遍历棋盘的所有位置,查看每一个位置上的元素是否满足Sudoku的要求,也就是每一行,每一列以及每个小9×9的区域是否存在相同的元素,如果存在相同的元素,即为不合法。对于判断一个元素是否在某一行,某一列或者某个小区域内,我的实现是将定义了9个整数代表每一列,9个整数代表每一行,9个元素代表了9个小的9×9的区域,因此,用每一个整数的第1到第九位表示某个元素是否在该列,该行或该小区域中。通过位操作可以判断该元素是否存在。
三.实现代码
#include <iostream>#include <vector>using namespace std;class Solution{private: bool isExist(int &Input, int Number) { if (Input & (1 << Number)) { return true; } Input = Input | (1 << Number); return false; }public: bool isValidSudoku(vector<vector<char> > &board) { int X_value[9] = {0}; int Y_value[9] = {0}; int Inside[9] = {0}; for (int Index_y = 0; Index_y < 9; Index_y++) { vector<char> &TmpRow = board[Index_y]; for (int Index_x = 0; Index_x < 9; Index_x++) { if (TmpRow[Index_x] == '.') { continue; } int TmpValue = TmpRow[Index_x] - '0'; // is valid in Index_x row if (isExist(X_value[Index_x], TmpValue)) { return false; } // is valid in Index_y col if (isExist(Y_value[Index_y], TmpValue)) { return false; } // is valid in 3*3 sub block if (isExist(Inside[Index_x / 3 + Index_y / 3 * 3] , TmpValue)) { return false; } } } return true; }};
四.体会
这道题基本上不需要什么算法,只是在考虑如何判断一个元素是否已经存在时需要稍微考虑下,我的实现用来27个整数的第1到第9位来判断一个元素是否已经存在。其实使用三个整数就基本上可以完成这样的任务了,只不过这样处理起来稍微有点复杂。
这道题也算是一道水题,可以用于练练手。
版权所有,欢迎转载,转载请注明出处,谢谢
1 0
- Leetcode_valid-sudoku
- LeetCode_Valid Sudoku
- leetcode_Valid Sudoku
- leetcode_Valid Sudoku and Sudoku Solver (数独游戏) _easy
- Leetcode_valid-parentheses
- Leetcode_valid-palindrome
- Leetcode_Valid Palindrome
- leetcode_Valid Palindrome
- leetcode_Valid Number
- leetcode_Valid Parentheses
- leetcode_Valid Anagram
- leetcode_Valid Anagram_easy
- LeetCode_Valid Parentheses
- LeetCode_valid-anagram
- leetCode_Valid Number
- leetcode_Valid Perfect Square
- Sudoku
- sudoku
- 新风格风格个
- Qt Creater 3.3.2 (Qt5.4.1) Win7安装调试器debugger
- 算法学习 - 选择排序的稳定性讨论(C++实现)
- 聚合优于继承
- LeetCode - Convert Sorted List to Binary Search Tree
- LeetCode_Valid Sudoku
- MFC动态创建窗口
- 惠普 envy dv4 5214tx 光盘安装centos6.4
- LeetCode - Implement strStr()
- 房间看电视可见富豪数据库
- io 流
- 黑马程序员——Objecttive-C学习笔记(四):Foundation Kit
- 拉格朗日乘子法和KKT条件
- LeetCode - Reverse Nodes in k-Group