【LeetCode】Valid Sudoku

来源:互联网 发布:视频格式转换软件下载 编辑:程序博客网 时间:2024/05/23 13:25

参考链接

http://blog.csdn.net/doc_sgl/article/details/13002461


题目描述

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.


这个题目并不是问有没有一种解决方案,而是问填进去的数字是否合理,只要保证填进去的数字一行,一列一大格里没重复数字就可以了。
bool isValidSudoku(vector<vector<char> > &board) {        // Note: The Solution object is instantiated only once.vector<vector<bool>> rows(9, vector<bool>(9,false));vector<vector<bool>> cols(9, vector<bool>(9,false));vector<vector<bool>> blocks(9, vector<bool>(9,false));for(int i = 0; i < 9; i++)for(int j = 0; j < 9; j++){if(board[i][j] == '.')continue;int num = board[i][j] - '1';if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num])return false;rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true;}return true;    }

Sudoku Solver

 Total Accepted: 6798 Total Submissions: 33090My Submissions

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.


A sudoku puzzle...


...and its solution numbers marked in red.

class Solution {public:    void solveSudoku(vector<vector<char> > &board) {        solveSudokuCore(board,0);    }    bool solveSudokuCore(vector<vector<char> > &board,int index)    {    if(index == 81) return true;        int m = index / 9, n = index%9;    if(board[m][n] != '.')    {    return solveSudokuCore(board,index+1);}    //printvecvec(board,"board");    //system("pause");    set<char> leftnum;    for(int i = 1;i<10;i++)    leftnum.insert((char)(i+'0'));      for(int i = 0;i<9;i++)   {   if(board[m][i] != '.')    leftnum.erase(board[m][i]);   }      for(int i = 0;i<9;i++)   {   if(board[i][n] != '.')    leftnum.erase(board[i][n]);   }   int r = (m/3)*3;   int c = (n/3)*3;   for(int i = 0;i<3;i++)   for(int j = 0;j<3;j++)   {   if(r+i != m && c+j != n && board[r+i][c+j] != '.')   leftnum.erase(board[r+i][c+j]);   }   set<char>::iterator it;   /*printf("++%d,%d :",m,n);   for (it=leftnum.begin(); it!=leftnum.end(); ++it)   {printf("%c  ", *it);   }   printf("\n");   */      for (it=leftnum.begin(); it!=leftnum.end(); ++it)   {   board[m][n] = *it;   //printf("%d,%d %c test\n",m,n,*it);   if(solveSudokuCore(board,index+1))   return true;//else//printf("%d,%d %c not ok\n",m,n,*it);   }   board[m][n] = '.';//////////////////////////////////////////////////////////////////   return false;    }};




推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/
0 0
原创粉丝点击