Hello everyone, like the title says I'm trying to finish implementing a solve function to solve a Sudoku Puzzle. So far I think I've figured out how to check the board to check for empty cells. What I can't figure out is how to test a value 1-9 against the column and row to make sure it is an acceptable value, and if not, backtrack to test another value. This problem would be a lot easier using a 2d array but of course the specifications require me to implement this using code that is already given. Below is the files used, along with the sudoku.cpp file which contains the code I have implemented so far, and pseudocode for what I am trying to accomplish. Any help pointing me in the right direction will be much appreciated. Thank you in advance.
int main(int argc, char** argv)
{
std::vector<int> squares;
for (unsigned int i = 0; i < Sudoku::GRID_SIZE; ++i)
{
int k;
std::cin >> k;
squares.push_back(k);
}
Sudoku puzzle(squares);
puzzle.solve();
if (puzzle.isSolved())
{
std::cout << puzzle << std::endl;
}
else
{
std::cout << "Unable to solve this puzzle" << std::endl;
}
return 0;
}
BACKTRACK.h
#pragma once
#ifndef __BACKTRACK_H__
#define __BACKTRACK_H__
void print(std::ostream& os) const
{
int k = 0;
for (int i = 0; i < ROW_SIZE; ++i)
{
for (int j = 0; j < COL_SIZE; ++j)
{
os << m_Problem[k] + 1 << ' ';
if (j % BOX_SIZE == BOX_SIZE - 1)
os << ' ';
++k;
}
os << std::endl;
if (i % BOX_SIZE == BOX_SIZE - 1)
os << std::endl;
}
}
private:
int square(int k) const
{
int r = row(k) / BOX_SIZE;
int c = column(k) / BOX_SIZE;
return c + BOX_SIZE * r;
}
int innerSquare(int k) const
{
int r = row(k) % BOX_SIZE;
int c = column(k) % BOX_SIZE;
return c + BOX_SIZE * r;
}
int row(int k) const
{
return k / ROW_SIZE;
}
int column(int k) const
{
return k % ROW_SIZE;
}
int posBySquare(int ou, int in) const
{
int r = (ou / BOX_SIZE) * BOX_SIZE;
int c = (ou % BOX_SIZE) * BOX_SIZE;
r += in / BOX_SIZE;
c += in % BOX_SIZE;
return posByColRow(c, r);
}
int posByColRow(int col, int row) const
{
return ROW_SIZE * row + col;
}
void Sudoku::solve()
{
// NOTE: Backtrack is 0-based, so you need to add 1 for the puzzle
m_IsSolved = false;
int count = 0;
while ((!m_IsSolved) && m_Problem.more())
{
for (int i = 0; i <81; i++)
{
for(int j=m_Initial[i]; j > 0 ;j--)
{
if(m_Initial[i] != 0)
{
m_Problem.prune(i+1);
}
else
{ // try a number
//check rows/columns to see if valid move
//if valid move m_Problem++
//if move not valid
//m_Problem.prune(i);
}
}
}
}
}
One final note is that I am only allowed edit the code in the SUDOKU.cpp file under the while loop.