xxxxxxxxxx
public class Solution {
public void SolveSudoku(char[][] board) {
}
}
xxxxxxxxxx
#include <iostream>
#include <vector>
using namespace std;
bool isValid(vector < vector < char >> & board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][col] == c)
return false;
if (board[row][i] == c)
return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)
return false;
}
return true;
}
bool solveSudoku(vector < vector < char >> & board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (solveSudoku(board))
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
int main() {
vector<vector<char>>board{
{'9', '5', '7', '.', '1', '3', '.', '8', '4'},
{'4', '8', '3', '.', '5', '7', '1', '.', '6'},
{'.', '1', '2', '.', '4', '9', '5', '3', '7'},
{'1', '7', '.', '3', '.', '4', '9', '.', '2'},
{'5', '.', '4', '9', '7', '.', '3', '6', '.'},
{'3', '.', '9', '5', '.', '8', '7', '.', '1'},
{'8', '4', '5', '7', '9', '.', '6', '1', '3'},
{'.', '9', '1', '.', '3', '6', '.', '7', '5'},
{'7', '.', '6', '1', '8', '5', '4', '.', '9'}
};
solveSudoku(board);
for(int i= 0; i< 9; i++){
for(int j= 0; j< 9; j++)
cout<<board[i][j]<<" ";
cout<<"\n";
}
return 0;
}
xxxxxxxxxx
//User function Template for Java
class Solution
{
static boolean isSafe(int[][] grid,int row,int col,int v){
for(int i=0;i<9;i++){
if(grid[i][col]==v)return false;
if(grid[row][i]==v)return false;
if(grid[3*(row/3)+i/3][3*(col/3)+i%3]==v)return false;
}
return true;
}
//Function to find a solved Sudoku.
static boolean SolveSudoku(int grid[][])
{
// add your code here
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(grid[i][j]==0){
for(int v = 1;v<=9;v++){
if(isSafe(grid,i,j,v)){
grid[i][j]=v;
if(SolveSudoku(grid)){
return true;
}
else{
grid[i][j]=0;
}
}
}
return false;
}
}
}
return true;
}
//Function to print grids of the Sudoku.
static void printGrid (int grid[][])
{
// add your code here
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
System.out.print(grid[i][j]+" ");
}
}
}
}
xxxxxxxxxx
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
}
};
xxxxxxxxxx
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function(board) {
};
xxxxxxxxxx
class Solution {
/**
* @param String[][] $board
* @return NULL
*/
function solveSudoku(&$board) {
}
}
xxxxxxxxxx
/**
Do not return anything, modify board in-place instead.
*/
function solveSudoku(board: string[][]): void {
};