您的位置:首页 > 其它

LeetCode 36 - Valid Sudoku

2016-03-01 16:41 344 查看

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 
'.'
.



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.

My Code

class Solution {
public:
bool checkCells(vector<char>& cells)
{
vector<int> count(9 , 0);
for (int j = 0; j < 9; j++)
{
if (cells[j] == '.')
continue;

int number = cells[j]-'1';
count[number]++;
if (count[number] > 1)
return false;
}

return true;
}

bool isValidSudoku(vector<vector<char> >& board) {
vector<char> cells;

// Check row
for (int i = 0; i < 9; i++)
{
if (checkCells(board[i]) == false)
return false;
}

// Check column
for (int i = 0; i < 9; i++)
{
cells.clear();
for (int j = 0; j < 9; j++)
cells.push_back(board[j][i]);

if (checkCells(cells) == false)
return false;
}

// Check box
for (int i = 0; i < 9; i += 3)
for (int j = 0; j < 9 ;j += 3)
{
cells.clear();
for (int ii = i; ii < i + 3; ii++)
for (int jj = j; jj < j + 3; jj++)
{
cells.push_back(board[ii][jj]);
}

if (checkCells(cells) == false)
return false;
}

return true;
}
};
Runtime: 16 ms



Test Case

5 3 . . 7 . . . .

6 . . 1 9 5 . . .

. 9 8 . . . . 6 .

8 . . . 6 . . . 3

4 . . 8 . 3 . . 1

7 . . . 2 . . . 6

. 6 . . . . 2 8 .

. . . 4 1 9 . . 5

. . . . 8 . . 7 9

True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: