Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to write sudoku game solution using OOPs in c++

+2 votes
asked Apr 2, 2019 by siddalinga reddy (140 points)

1 Answer

0 votes
answered Jan 21 by murali (200 points)
#include <iostream>
using namespace std;

class Sudoku {
private:
    static const int SIZE = 9;
    int board[SIZE][SIZE];

public:
    // Constructor
    Sudoku(int initialBoard[SIZE][SIZE]) {
        for (int i = 0; i < SIZE; i++)
            for (int j = 0; j < SIZE; j++)
                board[i][j] = initialBoard[i][j];
    }

    // Print the Sudoku board
    void printBoard() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                cout << board[i][j] << " ";
            }
            cout << endl;
        }
    }

    // Check if num can be placed at board[row][col]
    bool isSafe(int row, int col, int num) {
        // Check row & column
        for (int x = 0; x < SIZE; x++) {
            if (board[row][x] == num || board[x][col] == num)
                return false;
        }

        // Check 3x3 sub-grid
        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 (board[startRow + i][startCol + j] == num)
                    return false;

        return true;
    }

    // Find empty cell
    bool findEmptyCell(int &row, int &col) {
        for (row = 0; row < SIZE; row++)
            for (col = 0; col < SIZE; col++)
                if (board[row][col] == 0)
                    return true;
        return false;
    }

    // Solve Sudoku using Backtracking
    bool solve() {
        int row, col;

        if (!findEmptyCell(row, col))
            return true;  // Solved

        for (int num = 1; num <= 9; num++) {
            if (isSafe(row, col, num)) {
                board[row][col] = num;

                if (solve())
                    return true;

                board[row][col] = 0; // Backtrack
            }
        }
        return false;
    }
};
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...