Sudoku Solver填数

来源:互联网 发布:pp助手mac版工具箱 编辑:程序博客网 时间:2024/06/02 15:04

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.

  1. bool isValid(vector<vector<char> > &board, int a, int b) {  
  2.         int i,j;  
  3.         for(i = 0; i < 9; i++)  
  4.             if(i != a && board[i][b] == board[a][b])  
  5.                 return false;  
  6.   
  7.         for(j = 0; j < 9; j++)  
  8.             if(j != b && board[a][j] == board[a][b])  
  9.                 return false;  
  10.   
  11.         int x = a/3*3;  
  12.         int y = b/3*3;  
  13.         for(i = 0; i < 3; i++)  
  14.             for(j = 0; j< 3; j++)  
  15.                 if(x+i != a && y+j != b && board[x+i][y+j] == board[a][b])  
  16.                     return false;  
  17.         return true;  
  18.     }  
  19.     bool solveSudokudfs(vector<vector<char> > &board)  
  20.     {  
  21.         for(int i = 0; i < 9; i++)  
  22.             for(int j = 0; j < 9; j++)  
  23.             {  
  24.                 if(board[i][j] == '.')  
  25.                 {  
  26.                     for(int k = 1; k <= 9; k++)  
  27.                     {  
  28.                         board[i][j] = '0' + k;  
  29.                         if(isValid(board,i,j) && solveSudokudfs(board))  
  30.                             return true;  
  31.                         board[i][j] = '.';  
  32.                     }  
  33.                     return false;  
  34.                 }  
  35.             }  
  36.         return true;  
  37.     }  
  38.     void solveSudoku(vector<vector<char> > &board) {  
  39.         // Note: The Solution object is instantiated only once.  
  40.         solveSudokudfs(board);  
  41.     }  


0 0