Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character ‘.‘ .
Assume that there would be is only one unique solution.
A Sudoku Puzzle ...
... and its solution numbers marked in red.
The problem is to solve the Sudoku, using backtracking algorithm, in turn, search. Time: 92ms. The code is as follows:
classSolution { Public: BOOLIsValid (vector<vector<Char>>&board, size_t I, size_t j) { for(size_t x =0; X <9; ++x) { if(Board[x][j] = = Board[i][j] && x! =i)return false; } for(size_t y =0; Y <9; ++y) { if(Board[i][y] = = Board[i][j] && y! =j)return false; } for(size_t x =3* (I/3); X <3* (I/3) +3; ++x) { for(size_t y =3* (J/3); Y <3* (J/3) +3; ++y) { if(Board[x][y] = = Board[i][j] && x! = i && y! =j)return false; } } return true; } BOOLMakesolvesudoku (vector<vector<Char>>&Board) { for(size_t i =0; I <9; ++i) { for(size_t j =0; J <9; ++j) { if(Board[i][j] = ='.'){ for(intK =1; K <=9; ++k) {Board[i][j]= k +'0'; if(IsValid (board, I, J) &&Makesolvesudoku (board))return true; BOARD[I][J]='.'; } return false; } } } return true; } voidSolvesudoku (vector<vector<Char>>&Board) {Makesolvesudoku (board); }};
[Leetcode] #37 Sudoku Solver