knakul853

Untitled

Jun 21st, 2020
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     int row[10][256]={0};
  7.     int col[10][256]={0};
  8.     int square[4][4][256] = {0};
  9.     void solveSudoku(vector<vector<char>>& board) {
  10.        
  11.         int n = (int)board.size();
  12.         int m = (int)board[0].size();
  13.        
  14.         for(int i=0;i<n;i++)
  15.         {
  16.             for(int j=0;j<m;j++)
  17.             {
  18.                 char c = board[i][j];
  19.                 if(c != '.')
  20.                 {
  21.                     row[i][c] = col[j][c] = square[i/3][j/3][c] = 1;
  22.                 }
  23.             }
  24.         }
  25.        
  26.         solveSudoku(board, 0, 0);
  27.     }
  28.    
  29.     bool check(int i,int j, char val)
  30.     {
  31.         if(row[i][val] || col[j][val] || square[i/3][j/3][val]) return false;
  32.        
  33.         return true;
  34.     }
  35.      bool solveSudoku(vector<vector<char>>& board, int i, int j)
  36.      {
  37.          if( i == 9) return true;
  38.          
  39.          if( j == 9) return solveSudoku(board, i+1, 0);
  40.          
  41.          if(board[i][j] !='.') return solveSudoku(board, i, j+1);
  42.          
  43.          for( char c='1'; c<='9'; c++ )
  44.          {
  45.              if(check(i, j, c))
  46.              {
  47.                  board[i][j] = c;
  48.                  row[i][c] = col[j][c] = square[i/3][j/3][c] = 1;
  49.                  if(solveSudoku(board, i, j+1))
  50.                      return true;
  51.                  board[i][j] = '.';
  52.                  row[i][c] = col[j][c] = square[i/3][j/3][c] = 0;
  53.              }
  54.          }
  55.          
  56.          return false;
  57.      }
  58. };
Add Comment
Please, Sign In to add comment