C++ Sudoku using Backtracking/Recursion
Mar 18, 2014 at 4:59am UTC
My teacher wants us to make an NxN sudoku puzzle and solve it using random numbers from 1 to N. There can be no repeats in rows or column, everything else is fine. Recursion or backtracking has to be used. Here's what I have so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#include<iostream>
#include<time.h>
#include<cstdlib>
#include<cstdio>
using namespace std;
void fill_puzzle(int size);
void delete_puzzle(int **array, int size);
bool check_correct(int **array, int size);
bool check_correct(int **array, int size){
int temp=0;
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
for (int k=0;k<size;k++){
if (array[i][k]==array[i][j])
return false ;
else
return true ;
}
}
}
}
void fill_puzzle(int size){
int **array;
array=new int *[size];
for (int i=0; i<size; i++){
array[i]=new int [size];
}
srand((unsigned int )time(NULL));
if (check_correct(array,size)==false )
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
array[i][j]=(rand() % size);
fill_puzzle(size-1);
}
}
else {
for (int i=0;i<size;i++)
for (int j=0;j<size;j++)
cout << array[i][j];
}
delete_puzzle(array,size);
}
void delete_puzzle(int **array, int size){
for (int i=0; i<size; i++){
delete [] array[i];
}
delete []array;
}
int main(){
int size=0;
cout << "Hello, what size puzzle would you like to create? Please type a number. Example: 3 would make a 3x3 sudoku puzzle." <<endl;
cin >> size;
if (size > 0){
fill_puzzle(size);
}
else {
cout << "Invalid size. Must be greater than 0." <<endl;
exit (0);
}
return 0;
}
When I compile, I get no output except the bit where it asks the user for the size. Any help would be appreciated, thank you.
Last edited on Mar 18, 2014 at 5:08am UTC
Mar 18, 2014 at 6:04am UTC
Do you have to use backtracking/recursion?
Mar 18, 2014 at 12:41pm UTC
Yeah, it's what we are learning in class, so he wants us to know how to implement it.
Topic archived. No new replies allowed.