Become a leader in the IoT community!
Join our community of embedded and IoT practitioners to contribute experience, learn new skills and collaborate with other developers with complementary skillsets.
Join our community of embedded and IoT practitioners to contribute experience, learn new skills and collaborate with other developers with complementary skillsets.
What will be the output of this code?
“`C++
#include
#include
using namespace std;
bool isSafe(vector
// Check if the number is already present in the current row or column
for (int i = 0; i < 9; ++i) {
if (grid[row][i] == num || grid[i][col] == num) {
return false;
}
}
// Check if the number is already present in the current 3x3 subgrid
int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (grid[i + startRow][j + startCol] == num) {
return false;
}
}
}
return true;
}
bool solveSudoku(vector
int row, col;
bool isFilled = true;
for (row = 0; row < 9; ++row) {
for (col = 0; col < 9; ++col) {
if (grid[row][col] == 0) {
isFilled = false;
break;
}
}
if (!isFilled) {
break;
}
}
if (isFilled) {
return true; // Grid is completely filled
}
for (int num = 1; num <= 9; ++num) {
if (isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (solveSudoku(grid)) {
return true;
}
grid[row][col] = 0; // Backtrack
}
}
return false; // No solution found
}
void printGrid(vector
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
cout << grid[i][j] << " ";
}
cout << endl;
}
}
int main() {
vector
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (solveSudoku(grid)) {
cout << "Solution:\n";
printGrid(grid);
} else {
cout << "No solution exists.\n";
}
return 0;
}
```
CONTRIBUTE TO THIS THREAD