leetcode36Valid Sudoku

来源:互联网 发布:ios仿淘宝商品详情 编辑:程序博客网 时间:2024/06/09 14:26
// test36ValidSudoku.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "vector"
#include "iostream"
using std::cout;
using std::endl;
using std::vector;
bool isValidSudoku(vector<vector<char> > &board);
bool checkRowAndCol(vector<vector<char> > &board);
bool checkBlock(vector<vector<char> > &board);


int _tmain(int argc, _TCHAR* argv[])
{
vector<vector<char> > board = { { '6', '6', '3', '7', '2', '8', '9', '5', '1' },
                                 {'2', '5', '9', '4', '6', '1', '7', '3', '8'},
                                 {'7', '8', '1', '3', '5', '9', '6', '4', '2'},
                                 {'5', '3', '2', '1', '9', '7', '4', '8', '6'},
 { '9', '1', '4', '6', '.', '2', '5', '7', '3' },
 { '6', '7', '8', '5', '4', '3', '1', '2', '9' },
 { '8', '2', '6', '9', '7', '.', '3', '1', '4' },
 { '.', '4', '7', '2', '3', '6', '8', '9', '5' },
 { '9', '9', '5', '8', '1', '4', '2', '6', '7' } };
bool a = isValidSudoku(board);
cout << a << endl;
return 0;
}


bool isValidSudoku(vector<vector<char> > &board) 
{
return checkRowAndCol(board) && checkBlock(board);
}
bool checkRowAndCol(vector<vector<char> > &board)
{
int n = board.size();
int row[9];
int col[9];
for (int i = 0; i < n; i++)
{
memset(row, 0, n*sizeof(int));//清零操作,注意该语句的书写。
memset(col, 0, n*sizeof(int));
for (int j = 0; j < n; j++) //行检测
{
if (board[i][j] != '.')
{
if (row[board[i][j] - 49] != 0)
return false;
else
row[board[i][j] - 49] = 1;
}
}


for (int q = 0; q < n; q++) //列检测
{
if (board[q][i] != '.')
{
if (col[board[q][i] - 49] != 0)
return false;
else
col[board[q][i] - 49] = 1;
}
}
}
return true;
}
bool checkBlock(vector<vector<char> > &board)
{
int n = board.size();
int block[9];
for (int i = 0; i < (n / 3); i++)
{
for (int j = 0; j < (n / 3); j++)
{
memset(block, 0, n*sizeof(int));//清零操作
for (int q = 0; q <= 2; q++)
{
if (board[i * 3][j * 3 + q]!='.')
{
if (block[board[i * 3][j * 3 + q] - 49] != 0)
return false;
else
block[board[i * 3][j * 3 + q] - 49] = 1;
}
if (board[i * 3 + 1][j * 3 + q] != '.')
{
if (block[board[i * 3 + 1][j * 3 + q] - 49] != 0)
return false;
else
block[board[i * 3 + 1][j * 3 + q] - 49] = 1;
}
if (board[i * 3 + 2][j * 3 + q] != '.')
{
if (block[board[i * 3 + 2][j * 3 + q] - 49] != 0)
return false;
else
block[board[i * 3 + 2][j * 3 + q] - 49] = 1;
}
}
}
}
return true;
}
0 0
原创粉丝点击