您的位置:首页 > 其它

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(暴力破解):

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: