Question

In: Computer Science

Data Structure using C++ Complete and test the Sudoku problem main.cpp #include <iostream> #include <cmath> #include...

Data Structure

using C++ Complete and test the Sudoku problem

main.cpp


#include <iostream>
#include <cmath>
#include "sudoku.h"

using namespace std;

int main()
{
cout << "See Programming Exercise 18." << endl;
}

sudoku.cpp


#include <iostream>
#include "sudoku.h"

using namespace std;

sudoku::sudoku()
{
cout << "Write the definition. ." << endl;
}

sudoku::sudoku(int g[][9])
{
cout << "Write the definition." << endl;
}

void sudoku::initializeSudokuGrid()
{
cout << "Write the definition." << endl;
}

void sudoku::initializeSudokuGrid(int g[][9])
{
cout << "Write the definition. " << endl;
}

void sudoku::printSudokuGrid()
{
cout << "Write the definition." << endl;
}

bool sudoku::solveSudoku()
{
int row, col;

if (findEmptyGridSlot(row, col))
{   
for (int num = 1; num <= 9; num++)
{   
if (canPlaceNum(row, col, num))
{
grid[row][col] = num;
if (solveSudoku()) //recursive call
return true;
grid[row][col] = 0; //backtrack
}
}
return false;
}
else
return true; //there are no empty slots
}

bool sudoku::findEmptyGridSlot(int &row, int &col)
{
cout << "Write the definition."<< endl;
}

bool sudoku::canPlaceNum(int row, int col, int num)
{
cout << "Write the definition."<< endl;
}

bool sudoku::numAlreadyInRow(int row, int num)
{
cout << "Write the definition." << endl;
}

bool sudoku::numAlreadyInCol(int col, int num)
{
cout << "Write the definition." << endl;
}

bool sudoku::numAlreadyInBox(int smallGridRow, int smallGridCol,
int num)
{
cout << "Write the definition." << endl;
}

sudoku.h


//***************************************************************
// D.S. Malik
//
// This class specifies the functions to solve a sudoku problem.
//***************************************************************

class sudoku
{
public:
sudoku();
//default constructor
//Postcondition: grid is initialized to 0

sudoku(int g[][9]);
//constructor
//Postcondition: grid = g

void initializeSudokuGrid();
//Function to promt the user to specify the numbers of the
//partially filled grid.
//Postcondition: grid is initialized to the numbers
// specified by the user.

void initializeSudokuGrid(int g[][9]);
//Function to initialize grid to g
//Postcondition: grid = g;

void printSudokuGrid();
//Function to print the sudoku grid.

bool solveSudoku();
//Funtion to solve the sudoku problem.
//Postcondition: If a solution exits, it returns true,
// otherwise it returns false.
bool findEmptyGridSlot(int &row, int &col);
//Function to determine if the grid slot specified by
//row and col is empty.
//Postcondition: Returns true if grid[row][col] = 0;

bool canPlaceNum(int row, int col, int num);
//Function to determine if num can be placed in
//grid[row][col]
//Postcondition: Returns true if num can be placed in
// grid[row][col], otherwise it returns false.

bool numAlreadyInRow(int row, int num);
//Function to determine if num is in grid[row][]
//Postcondition: Returns true if num is in grid[row][],
// otherwise it returns false.

bool numAlreadyInCol(int col, int num);
//Function to determine if num is in grid[row][]
//Postcondition: Returns true if num is in grid[row][],
// otherwise it returns false.

bool numAlreadyInBox(int smallGridRow, int smallGridCol,
int num);
//Function to determine if num is in the small grid
//Postcondition: Returns true if num is in small grid,
// otherwise it returns false.

private:
int grid[9][9];
};

Solutions

Expert Solution

Here is my solution for the soduko problem with the tested output

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define UNASSIGNED 0
#define N 9
 
bool FindUnassignedLocation(int grid[N][N], int &row, int &col);
bool isSafe(int grid[N][N], int row, int col, int num);
 
/* assign values to all unassigned locations for Sudoku solution  
 */
bool SolveSudoku(int grid[N][N])
{
    int row, col;
    if (!FindUnassignedLocation(grid, row, col))
       return true;
    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] = UNASSIGNED;
        }
    }
    return false;
}
 
/* Searches the grid to find an entry that is still unassigned. */
bool FindUnassignedLocation(int grid[N][N], int &row, int &col)
{
    for (row = 0; row < N; row++)
        for (col = 0; col < N; col++)
            if (grid[row][col] == UNASSIGNED)
                return true;
    return false;
}
 
/* Returns whether any assigned entry n the specified row matches 
   the given number. */
bool UsedInRow(int grid[N][N], int row, int num)
{
    for (int col = 0; col < N; col++)
        if (grid[row][col] == num)
            return true;
    return false;
}
 
/* Returns whether any assigned entry in the specified column matches 
   the given number. */
bool UsedInCol(int grid[N][N], int col, int num)
{
    for (int row = 0; row < N; row++)
        if (grid[row][col] == num)
            return true;
    return false;
}
 
/* Returns whether any assigned entry within the specified 3x3 box matches 
   the given number. */
bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num)
{
    for (int row = 0; row < 3; row++)
        for (int col = 0; col < 3; col++)
            if (grid[row+boxStartRow][col+boxStartCol] == num)
                return true;
    return false;
}
 
/* Returns whether it will be legal to assign num to the given row,col location. 
 */
bool isSafe(int grid[N][N], int row, int col, int num)
{
    return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) &&
           !UsedInBox(grid, row - row % 3 , col - col % 3, num);
}
 
/* print grid  */
void printGrid(int grid[N][N])
{
    for (int row = 0; row < N; row++)
    {
        for (int col = 0; col < N; col++)
            cout<<grid[row][col]<<"  ";
        cout<<endl;
    }
}
 
/* Main */
int main()
{
    int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
                      {5, 2, 0, 0, 0, 0, 0, 0, 0},
                      {0, 8, 7, 0, 0, 0, 0, 3, 1},
                      {0, 0, 3, 0, 1, 0, 0, 8, 0},
                      {9, 0, 0, 8, 6, 3, 0, 0, 5},
                      {0, 5, 0, 0, 9, 0, 6, 0, 0},
                      {1, 3, 0, 0, 0, 0, 2, 5, 0},
                      {0, 0, 0, 0, 0, 0, 0, 7, 4},
                      {0, 0, 5, 2, 0, 6, 3, 0, 0}};
    if (SolveSudoku(grid) == true)
          printGrid(grid);
    else
        cout<<"No solution exists"<<endl;
    return 0;
}

Here is the output:

Hope this helps:).If you still have any doubt , feel free to discuss it in the comment sections.


Related Solutions

Please comments this C++ code and show screenshots of the outputs main.cpp #include<iostream> #include<vector> #include<string> #include"BST.h"...
Please comments this C++ code and show screenshots of the outputs main.cpp #include<iostream> #include<vector> #include<string> #include"BST.h" #include"BST.cpp" using namespace std; std::vector<std::string> tokenize(char line[]) {    std::vector<std::string> tok;        std::string word = "";        for (int i = 0; i < strlen(line); i++)        {            if (i == strlen(line) - 1)            {                word += line[i];                tok.push_back(word);                return tok;       ...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
C++ Download the attached program and complete the functions. (Refer to comments) main.cpp ~ #include #include...
C++ Download the attached program and complete the functions. (Refer to comments) main.cpp ~ #include #include #define END_OF_LIST -999 using namespace std; /* * */ int exercise_1() { int x = 100; int *ptr; // Assign the pointer variable, ptr, to the address of x. Then print out // the 'value' of x and the 'address' of x. (See Program 10-2) return 0; } int exercise_2() { int x = 100; int *ptr; // Assign ptr to the address of...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits>...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits> #include <vector> using namespace std; // // CLASS: NODE // class Node{ public: int value = 0; // our node holds an integer Node *next = nullptr; // our node has a pointer to the next Node Node(int i){ // contructor for our Node class value = i; // store a copy of argument "i" in "value" next = nullptr; // be sure next...
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using...
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using namespace std; // M x N matrix #define M 5 #define N 5 // Naive recursive function to find the minimum cost to reach // cell (m, n) from cell (0, 0) int findMinCost(int cost[M][N], int m, int n) {    // base case    if (n == 0 || m == 0)        return INT_MAX;    // if we're at first cell...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; class TowersOfHanoi { friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers); public: //constructor TowersOfHanoi(); //custom methods unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout); private: //custom methods void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux); //temporary variable unsigned _n_moves; //data const unsigned _n_towers; stack<unsigned>* _tower; }; #include "TowersOfHanoi.h" // ostream& operator<<(ostream& sink, const...
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using...
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using namespace std; int lastIndexOf(char *s, char target) { int n=strlen(s); for(int i=n-1;i>=0;i--) { if(s[i]==target) { return i; } } return -1; } void reverse(char *s) { int n=strlen(s); int i=0,j=n-1; while(i<=j) { char temp=s[i]; s[i]=s[j]; s[j]=temp; i++; j--; } return; } int replace(char *s, char target, char replacementChar) { int len=strlen(s); int total=0; for(int i=0;i<len;i++) { if(s[i]==target) { s[i]=replacementChar; total+=1; } } return total;...
C++ and Java Zoo File Manager I need to complete these files: #include <iostream> #include <jni.h>...
C++ and Java Zoo File Manager I need to complete these files: #include <iostream> #include <jni.h> using namespace std; void GenerateData() //DO NOT TOUCH CODE IN THIS METHOD { JavaVM *jvm; // Pointer to the JVM (Java Virtual Machine) JNIEnv *env; // Pointer to native interface //================== prepare loading of Java VM ============================ JavaVMInitArgs vm_args; // Initialization arguments JavaVMOption* options = new JavaVMOption[1]; // JVM invocation options options[0].optionString = (char*) "-Djava.class.path="; // where to find java .class vm_args.version = JNI_VERSION_1_6;...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using namespace std; const int CWIDTH = 26; int main() {    int choice;    double convertFoC, converCtoF;    double starting, endvalue, incrementvalue;    const int CWIDTH = 13;    do {       cin >> choice;    switch (choice)    {        cin >> starting;    if (starting == 28){       cout << "Invalid range. Try again.";    }    while (!(cin >> starting)){       string  garbage;       cin.clear();       getline(cin, garbage);       cout << "Invalid data Type, must be a number....
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT