LeetCode之“散列表”:Valid Sudoku
2015-06-20 16:20
344 查看
题目链接
题目要求:
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
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.
这道题解法暂没有比较巧妙的,所以下边程序所用方法就是Brute Force(暴力破解):
题目要求:
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
'.'.
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.
这道题解法暂没有比较巧妙的,所以下边程序所用方法就是Brute Force(暴力破解):
class Solution { public: int charToInt(char c) { char str[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; int intStr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for(int i = 0; i < 9; i++) { if(c == str[i]) return intStr[i]; } return -1; } bool isValidSudoku(vector<vector<char>>& board) { unordered_map<int, int> hashMap; for(int i = 1; i < 10; i++) hashMap[i] = 0; // row by row for(int i = 0; i < 9; i++) { for(int k = 0; k < 10; k++) hashMap[k] = 0; for(int j = 0; j < 9; j++) { int tmp = charToInt(board[i][j]); if(tmp != -1) { hashMap[tmp]++; if(hashMap[tmp] > 1) return false; } } } // column by column for(int j = 0; j < 9; j++) { for(int k = 1; k < 10; k++) hashMap[k] = 0; for(int i = 0; i < 9; i++) { int tmp = charToInt(board[i][j]); if(tmp != -1) { hashMap[tmp]++; if(hashMap[tmp] > 1) return false; } } } // 3*3 boxes by 3*3 boxes for(int i = 0; i < 9; i += 3) { for(int j = 0; j < 9; j += 3) { for(int k = 0; k < 10; k++) hashMap[k] = 0; for(int m = i; m < i + 3; m++) for(int n = j; n < j + 3; n++) { int tmp = charToInt(board[m] ); if(tmp != -1) { hashMap[tmp]++; if(hashMap[tmp] > 1) return false; } } } } return true; } };
相关文章推荐
- UVa 11346 Probability
- JavaWeb学习笔记——Tomcat配置
- Pascal's Triangle II
- hdu 2112 map+Dijkstra
- poj -- 2001 Shortest Prefixes (Trie 树)
- Hadoop集群(第6期)_WordCount运行详解
- Android ListView 单条刷新方法实践及原理解析
- bzoj3672
- PHP数组与对象之间用递归递归转换
- Hadoop集群(第5期)_Hadoop安装配置
- Pascal's Triangle
- 【BUAA 591】The Last Alpha Star
- Hadoop集群(第4期)_SecureCRT使用
- IO流学习二
- 最小生成树
- android应用的单元测试
- Esper入门简介:二 个人对它的理解
- 毕业课题之----HOG+SVM相关函数的解释
- SQL Server 有关EXCEPT和INTERSECT使用
- Bash的类型(交互、登录)及其相关配置文件