您的位置:首页 > 编程语言 > C语言/C++

LeetCode 35. Valid Sudoku

2014-06-24 02:34 309 查看
数独规则:

考察每行、每列、以及九个九宫格中的任意一个(题中已用粗线分割),都不包含重复的数字(即至多只有一个1, 2, 3, ..., 9)

代码:

class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
vector<int> cnt(9, 0);

for (int i = 0; i < 9; ++ i)
{
cnt.assign(9, 0);
for (int j = 0; j < 9; ++ j)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
for (int j = 0; j < 9; ++ j)
{
cnt.assign(9, 0);
for (int i = 0; i < 9; ++ i)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
return square_judge(0, 0, board) && square_judge(0, 3, board) && square_judge(0, 6, board)
&& square_judge(3, 0, board) && square_judge(3, 3, board) && square_judge(3, 6, board)
&& square_judge(6, 0, board) && square_judge(6, 3, board) && square_judge(6, 6, board);
}
private:
bool square_judge(int x, int y, const vector<vector<char> > &board)
{
vector<int> cnt(9, 0);
for (int i = 0; i < 3; ++ i)
{
for (int j = 0; j < 3; ++ j)
{
if (board[x+i][y+j] == '.')
{
continue;
} else if ( ++ cnt[board[x+i][y+j] - '1'] > 1)
{
return false;
}
}
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode sudoku C++