Sudoko Code:
#include <iostream>
using namespace std;
const int N = 9;
// Function to print the Sudoku grid
void printGrid(int grid[N][N]) {
// Loop through each row and column to print the numbers
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
cout << grid[row][col] << " ";
}
cout << endl;
// Move to the next line after each row
}
}
// Function to solve the Sudoku using backtracking
bool solveSudoku(int grid[N][N]) {
// Find an empty location (a cell with value 0)
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
if (grid[row][col] == 0)
{
// Try filling the empty cell with numbers from 1 to 9
for (int num = 1; num <= 9; num++)
{
// Check if it's safe to place 'num' at the current cell
bool isSafe = true;
// Check if 'num' already exists in the
// current row or column
for (int i = 0; i < N; i++)
{
if (grid[row][i] == num || grid[i][col] == num)
{
isSafe = false;
break;
}
}
// If 'num' is safe to place, recursively try
// solving the rest of the puzzle
if (isSafe)
{
grid[row][col] = num;
if (solveSudoku(grid))
{
return true;
}
grid[row][col] = 0; // Backtrack if the current placement doesn't lead to a solution
}
}
return false; // No number from 1 to 9 fits here, so return false
}
}
}
return true; // All cells are filled, puzzle is solved
}
int main() {
int grid[N][N];
cout << "Enter the Sudoku puzzle (use 0 for empty cells):\n";
// Input the Sudoku puzzle
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> grid[i][j];
}
}
// Solve the Sudoku puzzle
if (solveSudoku(grid)) {
cout << "Sudoku puzzle solved:\n";
// Print the solved Sudoku puzzle
printGrid(grid);
} else {
cout << "No solution exists for the Sudoku puzzle.\n";
}
return 0;
}
No comments:
Post a Comment
Fell free to write your query in comment. Your Comments will be fully encouraged.