Sudoku Grid Generator - c

I have just started making my Sudoku game and I have made this function grid for creating a 6x6 Sudoku grid. I have used the rand() function for different numbers in each cell (currently it will only check rows for repetition of numbers). rand() is also used for random numbers of empty cells in each grid.
The problem is that sometimes the grid is perfect 6x6 and without any number repeating (in rows only), however, sometimes in some cells there are garbage values generated and sometimes the number of columns is increased. I don't understand what is causing the problem?
The Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void grid(void) {
int cell[6][6], row, col, s, i, j;
char in = 'A';
srand(time(NULL));
for (row = 0; row <= 5; row++) {
printf("\t\t\t[ |");
for (col = 0; col <= 5; col++) {
s = rand() % 6 + 1;
if (s % 2 == 0)
{
cell[row][col] = rand() % 6 + 1;
for (j = 0; j<col; j++) {
if (cell[row][j] == cell[row][col]) {
col--;
continue;
}
}
}
else { printf(" | ", in++); continue; }
printf(" %d | ", cell[row][col]);
}
printf("]\n\n");
}
}
int main()
{
grid();
}

They are too many syntax errors in the code you post, and the format is quite horrible. Try editing it so we can help you !
col--;
Maybe this is your problem, because if you col--; in your for (col = 0; col < 6; col++) loop, you will do more than 6 iterations.

I know this question is old, but a commenter here did say to wait at least 1 hour...
To answer your question directly:
You get garbage values because you do not set values for cell when !(s % 2 == 0).
You get more than 6 entries per row because your c-- statement causes the col loop to execute more than 6 times (and you printf each time).
If you want to maintain the general structure of your logic, then do this in two passes - fill cell completely and then print the whole thing. However, there are other problems. You probably want to remove the s % 2 == 0 check completely, and the first continue could be a break (or a goto if you really want to make people angry).

Related

C 100 Prisoners riddle, something wrong with my code

(If you already know what the riddle is about just read the last 2 lines)
I saw a video about a riddle which is called "The 100 prisoners riddle" it essentially tells you that a bunch of prisoners (only one person at a time) get into a room, this room has boxes that are ordered correctly from 1 to a 100 but the numbers inside the boxes are random and each prisoner getting into the room is numbered from 1 to a 100 too, so each prisoner has to pick the box that has his number, each prisoner has a set of tries (50 tries) if he opened 50 boxes and he didn't find his number he loses! for example prisoner number 1 gets in the room and he has to find the box that has his number .. it might be box number 7 or 19 or 27 who knows! so it's just a game of luck .. or is it? the game has strategies and ways to mathematically solve the puzzle but that's not my problem here, I just wanna program the game in C and solve the puzzle for myself, the code has a lot of holes in it so look closely into it and find what's the problem, THANK YOU ALL :)!
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j = 0, k = 0, counter = 0;
int boxes[10];
int boxEntered;
for (i = 0; i <= 10; i++) \\ numbering the array
boxes[i] = i;
for (i = 0; i <= 10; i++) {
int temp = boxes[i];
int randomIndex = (rand() % 10); \\ shuffling the boxes to put random numbers
boxes[i] = boxes[randomIndex];
boxes[randomIndex] = temp;
}
for (i = 0; i <= 10; i++) {
printf("%d : (%d)\n", boxes[i], i); \\ print the boxes randomized and their index ordered
}
printf("You only have 5 tries!\n");
while (k != 5) {
while (j < 10) {
printf("Pick a box number between 0 and 10 (You are number %d)\n",counter);
scanf("%d",&boxEntered);
if (boxes[boxEntered] == boxes[counter]) {
printf("\nYou succeded, PROCEED TO NEXT PRISONER\n");
j++; \\ go to the next iteration
k = 0; \\ set tries back to 0
counter++;
} else
printf("Try again\nThe box you entered had number %d\n",boxes[boxEntered]);
k++;
if (k == 5) { \\ if player prisoner fails 5 times you break the loop
break;
}
}
}
if (counter == 10) { \\ if last prisoner was reached successfully then game is won
printf("You are freed!");
} else {
printf("You are going back heheheheheh!\n")
}
return 0;
}
As you can see in this picture the output doesn't make any sense at all and i have no idea what is wrong here..
From your code's logic, you should replace
boxes[boxEntered] == boxes[counter]
with
boxes[boxEntered] == counter
This is because counter here seems to represent a prisoner. Taking boxes[counter] will give you a box, which isn't what you want; you're trying to see if the box matches the current prisoner.
Another important note is the following code will go out of bounds for your array, causing undefined behaviour:
for (i = 0; i <= 10; i++) boxes[i] = i;
boxes is declared as having size 10, and therefore taking boxes[10] goes out of bounds; the maximum is boxes[9].
To fix this, you can index your arrays starting from 1. To do this in C, instead of declaring boxes[10], use boxes[11]. This will ensure you can access boxes[10].
You can then change your loops to start from 1, so something like:
for (i = 1; i <= 10; i++) boxes[i] = i;
Be sure to make this change for every array and for loop in your code.

How to fill an empty sudoku board in C

I got an assignment to write a program that fills an empty sudoku board and prints it out.
The tools that we have are only functions, arrays and pointers. No recursion, no search and sort algorithms to improve the time complexity.
So far I thought to use two dimension array for the board and go over every row in a nested "for" loop.
Every time I fetch a number with a random function and check a row, a column and a square (3X3), and if all of them pass then I fill the number.
My problem is that, that way it takes the code a very long time to solve, and I don't know if I'm doing it right. I didn't see a solution of my code yet, even after leaving it to run more than 5 minutes. I thought maybe somehow to use a histogram of numbers from 1-9 that maps which numbers already used to somehow change the use of fetching random numbers, but I'm not really sure how to use it and if it's even right to do so. Basically I'm stuck.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define MATRIX_SIZE 9
#define MAX_NUM 9
void solve_sudoku(int board[MATRIX_SIZE][MATRIX_SIZE]);
void print_sudoku(int board[MATRIX_SIZE][MATRIX_SIZE]);
int rowCheck(int num, int board[][MATRIX_SIZE], int row);
int columnCheck(int num, int board[][MATRIX_SIZE], int row);
int squareCheck(int num, int board[][MATRIX_SIZE], int row, int col);
int giveNum(void);
void main()
{
srand(time(NULL));
int board[MATRIX_SIZE][MATRIX_SIZE];
/*{
0,0,0,0,0,4,0,0,0,
0,6,8,0,0,0,5,0,0,
0,2,0,0,0,0,0,7,6,
6,0,0,0,0,0,8,9,0,
0,0,5,2,6,0,0,0,0,
0,0,0,9,0,0,1,0,0,
0,0,0,0,0,7,0,5,0,
0,4,0,0,0,0,0,0,1,
0,0,0,0,5,1,4,0,0
};*/
for (int row = 0; row < MATRIX_SIZE; row++)
for (int col = 0; col < MATRIX_SIZE; col++)
board[row][col] = -1;
solve_sudoku(board);
print_sudoku(board);
}
void solve_sudoku(int board[MATRIX_SIZE][MATRIX_SIZE])
{
int rowCh, colCh, sqrCh, num, square = 0;
for (int row = 0; row < MATRIX_SIZE; row++)
{
for (int col = 0; col < MATRIX_SIZE; col++)
{
if (square > 2)
square = 0;
while(1)
{
num = giveNum();
rowCh = rowCheck(num, board, row, col);
if (!rowCh)
continue;
colCh = columnCheck(num, board, row, col);
if (!colCh)
continue;
sqrCh = squareCheck(num, board, row, col-square);
if (!sqrCh)
continue;
break;
} //while (!rowCh || !colCh || !sqrCh);
square++;
board[row][col] = num;
}
}
}
void print_sudoku(int board[MATRIX_SIZE][MATRIX_SIZE])
{
printf("Sudoku solution:\n");
for (int i = 0; i < MATRIX_SIZE; i++)
{
for (int j = 0; j < MATRIX_SIZE; j++)
printf("%d ", board[i][j]);
printf("\n");
}
}
int giveNum(void)
{
int num = rand() % MATRIX_SIZE + 1;
return num;
}
int rowCheck(int num, int board[][MATRIX_SIZE], int row)
{
for (int col = 0; col < MATRIX_SIZE; col++)
{
if (num == board[row][col])
return 0;
}
return 1;
}
int columnCheck(int num, int board[][MATRIX_SIZE], int col)
{
for (int row = 0; row < MATRIX_SIZE; row++)
{
if (num == board[row][col])
return 0;
}
return 1;
}
int squareCheck(int num, int board[][MATRIX_SIZE], int row, int col)
{
for (int i = row; i < row + sqrt(MATRIX_SIZE); i++)
for (int j = col; j < col + sqrt(MATRIX_SIZE); j++)
if (board[i][j] == num)
return 0;
return 1;
}
I strongly doubt that you will have much luck with a pure random approach. There are so many combinations so that chance of hitting a valid solution is very little. Instead you'll most likely end in a dead-lock where there is no valid number to put in current position... then you just have an endless loop.
Anyway... here is a bug:
For the squareCheck function to work, it's required that col and row identifies the upper-left corner. For col you ensure that using square but for row you don't.
In other words, your check isn't correct.
Instead of using "the square method" consider to put these lines in the start of the function:
row = row - (row % 3);
col = col - (col % 3);
There's a loop while(1) where you pick a random number and determine if it is valid in the current position.
It's quite possible to get to a dead end here.
You can have easily filled in numbers that while valid individually leave the puzzle insoluble.
You need some method of backtracking if you get 'stuck' or detecting that it will get stuck.
The 'common' approach is to hold a 9x9 matrix of sets holding a subset of 1-9 which are the untried values. When a value is set (at start) or tried (during solve) you check the constraints and remove the value being tried from its column, row and square.
Start with a 9x9 grid all cells initialised to the full range [1-9].
If you set a cell to (say) 5 remove 5 from all cells in that column, row and sub-square.
If that leaves any cell with the empty set, the puzzle is insoluble.
When solving only pick from the set of 'remaining possible values' rather than rand [1-9].
However it still may be that a trial makes the puzzle insoluble and needs to go back a cell (or more) to come forward again.
The easy way to do that would be recursion. But that's ruled out by the Exercise.
So it looks like some kind of Undo stack is required.
Here is a way to generate a random suduko.
// Check that no number 1..9 is present twice in a column
int colok(int s[][9])
{
for (int col=0; col<9; ++col)
{
for (int n=1; n<=9; ++n)
{
int cnt = 0;
for (int i=0; i<9; ++i)
{
if (s[i][col] == n)
{
if (cnt > 0) return 0;
cnt = 1;
}
}
}
}
return 1;
}
// Check that no number 1..9 is present twice in a 3x3 block
int blockok(int s[][9])
{
for (int row=0; row<9; row += 3)
{
for (int col=0; col<9; col +=3)
{
for (int n=1; n<=9; ++n)
{
int cnt = 0;
for (int i=0; i<3; ++i)
{
for (int j=0; j<3; ++j)
{
if (s[i + row][j + col] == n)
{
if (cnt > 0) return 0;
cnt = 1;
}
}
}
}
}
}
return 1;
}
void p(int s[][9])
{
for (int i=0; i<9; ++i)
{
for (int j=0; j<9; ++j)
{
printf("%d ", s[i][j]);
}
puts("");
}
}
#define MAX_LOOP 10000000
void makerow(int s[][9], int r)
{
int loops = 0;
while(1)
{
++loops;
// FY Shuffle row (this ensures that rows are always valid)
int a[] = {1,2,3,4,5,6,7,8,9};
int max = 8;
while(max)
{
int t = rand() % (max + 1);
int tmp = a[t];
a[t] = a[max];
a[max] = tmp;
--max;
}
// Save row
for (int i=0; i<9; ++i)
{
s[r][i] = a[i];
}
// Check whether it's valid
if (colok(s) && blockok(s))
{
// It's valid so stop here
break;
}
// Stop if too many loops
if (loops > MAX_LOOP)
{
puts("I'm so tired...");
exit(1);
}
}
printf("loops %d\n", loops);
}
int main(void)
{
srand((int)time(0));
int s[9][9] = { 0 };
for (int i=0; i<9; ++i)
{
printf("Make row %d\n", i);
makerow(s, i);
}
p(s);
return 0;
}
Possible output:
Make row 0
loops 1
Make row 1
loops 27
Make row 2
loops 1090
Make row 3
loops 3
Make row 4
loops 1019
Make row 5
loops 5521
Make row 6
loops 96
Make row 7
loops 66727
Make row 8
loops 498687
7 5 2 4 6 8 3 1 9
3 4 6 9 1 7 8 2 5
8 1 9 3 2 5 7 6 4
9 6 3 8 7 4 2 5 1
1 8 5 2 9 3 6 4 7
2 7 4 1 5 6 9 8 3
6 9 7 5 4 2 1 3 8
5 2 8 7 3 1 4 9 6
4 3 1 6 8 9 5 7 2
But notice... it happens that no solution can be generated.. then the output is:
Make row 0
loops 1
Make row 1
loops 37
Make row 2
loops 2957
Make row 3
loops 16
Make row 4
loops 2253
Make row 5
I'm so tired...
In order to avoid recursion you can try to navigate the solution space by levels. That requires a Queue, in which you add the next possible states from a given one (just extracted from the queue) and you mark the already visited ones (e.g. with the selected numbers) In this way you only build a single loop (no nested loops required) and you can generate all the possible solutions (but you can stop at the first that just generates a valid position)
Thanks for all of your responses. There is an update: I found a bug that made me a lot of problems, The bug was that I defined : columnCheck function that receives variable row and I called the function this way: " columnCheck(num, board, row, col); ", so the bug is that in the definition I need to give only 3 arguments, when I called the function accidently with 4 and also gave the columCheck the row instead the column. Also rowCheck was called with 4 arguments instead of 3 as defined. Can someone explain why the debugger didn't warn me about that ?
Also I changed the giveNum() function to this one:
int giveNum(void)
{
int static num = 1;
if (num > 9)
num = 1;
return num++;
}
Now it's not random but it fills the sudoku.
Since a lot of people asked the instructor how to do it, he replied that this kind of solution will be fine for now, However I will take the challenge to solve it with your suggestions.

C - Entering values for 2d Array using for loop produces different values than entered

I have this simple program I am working on in class, it initialized a 3x5 2d Array of integers whose values are inputted for each cell by the user. The program then calls a function which runs through the array with a for loop to display each value, then calls a function which again uses a for loop to double every value, and calls the previous display function to show the array again.
All of this seems to be working, however I am consistently getting odd outputs for certain areas when initializing the values for the 2dArray.
For example: Entering 5 rows of "1, 2, 3" and then calling the display function produces this as output:
1,1,2,
1,2,3,
1,2,3,
1,2,5,
1,2,3
Further more, the doubling function produces further strange results but only in the areas where the output was different from what the user had inputted.
Output of the double function on the array I just posted displays as:
2,4,8
2,4,6
2,4,6
2,4,10,
4,8,6
The only real mathematical operation in the entire program is in the doubling functions, where it runs through a for loop setting the value of "array[j][i] = (array[j][i] = array[j][i] * 2)"
I cannot for the life of me figure out which part of the program I've written would cause the user inputs to change to what has been displayed. Inputting values other than "1,2,3" produces similarly odd results. Anyone have any idea what is wrong here? I feel like it must be a very simple mistake I am missing. Here is my source code:
#include <stdio.h>
#include <stdlib.h>
void displayArray(int array[][4]);
void doubleArray(int array[][4]);
int main() {
int dArray[2][4];
int i, j, k;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
printf("Enter a value for the array at position %d,%d.\n", j, i);
scanf("%d", &dArray[j][i]);
}
}
printf("Displaying your original array...\n");
displayArray(dArray);
printf("Doubling your array...\n");
doubleArray(dArray);
printf("Displaying your doubled array....\n");
displayArray(dArray);
system("pause");
}
void displayArray(int array[][4]){
int i, j;
for(i = 0; i <= 4; i++){
printf("\n");
for(j = 0; j <= 2; j++){
if(j == 2 && i == 4){
printf("%d", array[j][i]);
}
else{
printf("%d,", array[j][i]);
}
//system("pause");
}
}
printf("\n");
}
void doubleArray(int array [][4]){
int i, j;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
array[j][i] = (array[j][i] * 2);
//printf("%d\n", array[j][i]);
}
}
}
It's all in one .c file, and I am using devc++ if that makes any difference.
To calculate the DIMENSIONS of your 2D C arrays you have to count how many columns and how many rows there are. In your examples, it is 3 columns and 5 rows, and those are the values you must enter in your array definition:
int array[3][5]
Then, because C starts indexing with 0 offset, you can referr to the elements of the array using the columns 0 to 2 (that is, 3 columns) and rows 0 to 4 (that is, 5 rows). As other people said, this can be achieved using "lower than the limit" (correct: <3 for the columns, <5 for the rows) instead of "lower or equal than the limit" (incorrect, out of bounds: <=3 for the columns, <=5 for the rows).

Most effective way to find combinations in C

#include <stdio.h>
#include <stdlib.h>
int chessboard[8][8];
int indicator, x, i, j, b, checksum, testerint, temp, row, column;
int rescounter, resstarter;
void togglecolumn(int columnumber) {
//
for (j = 0; j < 8; j++) {
//
chessboard[j][columnumber] = toggleint(chessboard[j][columnumber]);
}
}
void togglerow(int rownumber) {
//
for (j = 0; j < 8; j++) {
//
chessboard[rownumber][j] = toggleint(chessboard[rownumber][j]);
}
}
void fulltoggle(int i, int j) {
//
togglerow(i);
togglecolumn(j);
chessboard[i][j] = toggleint(chessboard[i][j]);
}
int toggleint(int a) {
//
if (a == 0) {
b = 1;
}
if (a == 1) {
b = 0;
}
return b;
}
void fillchessboard() {
x = 1;
//
for (i = 0; i < 8; i++) {
x = toggleint(x);
for (j = 0; j < 8; j++) {
//
chessboard[i][j] = x;
x = toggleint(x);
}
}
}
void showchessboard() {
//
printf("------------------- \n \n");
for (i = 0; i < 8; i++) {
//
for (j = 0; j < 8; j++) {
//
if (j == 7) {
//if end of the row
printf("%d \n", chessboard[i][j]);
} else {
//
printf("%d ", chessboard[i][j]);
}
}
}
printf("\n \n");
printf("------------------- \n \n");
}
int checkboard() {
checksum = 0;
for (i = 0; i < 8; i++) {
//
for (j = 0; j < 8; j++) {
//
if (chessboard[i][j] == 1) {
//
return 1;
}
}
}
return 0;
}
void rowcolindicator(int i) {
//
if (i % 8 == 0) {
column = 7;
row = i / 8 - 1;
} else {
row = i / 8;
column = i % 8 - 1;
}
}
// for proper operation i should be chosen 0
int recurfuntion(int i, int stepcounter) {
if (stepcounter != 0) {
stepcounter--;
temp = i;
for (i = temp + 1; i < 65; i++) {
//do row and column for
rowcolindicator(i);
fulltoggle(row, column);
recurfuntion(i, stepcounter);
}
if (i == 65) {
i = temp++;
rowcolindicator(temp);
fulltoggle(row, column);
stepcounter++;
}
} else {
//
temp = i;
for (i = temp + 1; i < 65; i++) {
//do row and column for i code and return iteration number if board turns all right
rowcolindicator(i);
fulltoggle(row, column);
if (checkboard() == 0) {
//
showchessboard();
return 1;
} else {
//
fulltoggle(row, column);
}
}
if (i == 65) {
i = temp++;
rowcolindicator(temp);
fulltoggle(row, column);
stepcounter++;
//showchessboard();
}
}
}
int main(int argc, char *argv[]) {
fillchessboard();
showchessboard();
indicator = checkboard();
printf("indicator is %d \n", indicator);
for (rescounter = 0; rescounter < 1000; rescounter++) {
fillchessboard();
printf("iiteration number: %d \n", rescounter);
if (recurfuntion(0, rescounter) == 1) {
printf("iteration number is %d so is the answer :) \n", rescounter);
}
}
system("PAUSE");
return 0;
}
I am trying solve this problem: "You have an 8x8 table on a computer screen with all squares colored to white. In each step you will select any square and as a result all the squares on the same row and column -including the selected square itself- will switch their colors (white becomes black, and black becomes white).
What is the minimum number of steps required for obtaining a standard colored chessboard?"
To do that, I percieved the chessboard into 64 pieces(8x8) and calculating all the combinations of this 64s cluster from 1 to 64. (I know the answer is between 1 and 64).
My method is to begin from the end(chessboard) through to all white. So I fill the board with ones(black) and zeros(white) and construct the chessboard in function fillchessboard() successfully. And I can perfectly toggle row and the column the initial square I choose is on.
Checking method if all board is white is checkboard(). This function returns indicator as 0 if all board is white, 1 if not. I start from little combinations to bigger combinations and check the board in each step. So when the indicator returns as 0 for the first time, it will be the smallest iteration number to make the board all white and be the answer of the question.
So far, my code works and in 10 hours it is able to step up to 10th iteration. However it will take more and more time so 11th iteration will take about 10 hours and 12th iteration will take 20 hours and so on... My question is, is there any method to these instructions more fast and effective? I can not wait for a week to solve this. I d appreciate any help. Thanks!
First let's do some naming:
c_{i,j} is the cell at intersection of row i and column j.
cross_{i,j} is the set: { c_{r,c} / r=i or c=j }. It is the cross of all cells from row i union column j. It contains an odd number of cells.
odd(cross_{i,j}) is a function which returns 0 if there is an even number of black cells in cross_{i,j} and 1 if there is an odd number of black cells.
Let's consider the effect of selecting cell c_{i,j}:
It will switch an odd number of cells in cross_{i,j} and so it will switch the value of odd(cross_{i,j}).
For all other "crosses" the number of cells impacted will be even and so the value of odd(cross_{k,l}) for any (k,l) \neq (i,j) will not change.
The reason for point 2 is that there are only 3 cases for the intersection of cross_{k,l} with cross_{i,j}:
It is a whole row, with an even number of cells.
It is a whole column with an even number of cells.
It is one cell for row k and one cell for column l.
So for every possibility an even number of cells change colors, and so the value of odd(cross_{k,l}) doesn't change.
So the only way to switch the value of odd(cross_{i,j}) is to select c_{i,j}.
At the end of the game there are 32 crosses which have switched value. So the minimal number of steps for any solution is 32.
Now, the previous reasoning also show that selecting the 32 cells of interest will produce the final checkerboard state.
So this is a minimal solution.
I'm sorry but there is no programming here :)
This isn't a solution, but some pointers that should help reduce the complexity (but not the difficulty) of the problem.
The chess board has 2^64 different states.
There are some properties of a chess board that will help you reduce the number of interesting states.
Each move flips 15 tiles (an odd number). Since you start and end with an even number of white tiles you know that the total number of moves is even.
Also, the order you perform the moves in is irrelevant. And selecting the same square twice reverses the previous flip. So we only need to figure out which of the 64 tiles to select.
So we can use 64 bits to represent the solution and each bit represents either a selected tile or an unselected tile. We could use a 64-bit long to store a possible solution.
Also, if you use a 64-bit long to store the state of the board, each step is an XOR with a number that flips the right 15 tiles (a number that has those 15 bits set).
A chessboard is symmetrical. It doesn't matter if you turn it or mirror it. The state would be the same. This further reduces the complexity, because it proves that if X is a solution then the complement of X is also a solution. So if no solution has been found with 32 pieces selected, then no solution exists.
My intuition (or rather the symmetry) suggests that the solution, if one exists) should be a multiple of 8 and be either 8, 16, or 32 with 16 being the most probable. I have no proof for this, however. I should be fairly easy to prove that no solution exists in 8 moves (and you have proved this by using brute force - provided your program is correct).

Sudoku: checking 3x3 grids for repeating values

I have worked for a sudoku puzzle in C but I'm stuck in one problem: Checking every 3x3 grid for not having duplicate values.
Here is my code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int v[10][10];
//Matrix start from 1 and end with 9
//So everywhere it should be i=1;i<=9 not from 0 to i<9 !!!
//Display function ( Display the results when it have)
void afisare()
{
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++)
printf("%2d",v[i][j]);
printf("\n");
}
printf("\n");
}
//Function to check the valability of value
int valid(int k, int ii, int jj)
{
int i;
//Check for Row/Column duplicate
for(i = 1; i <= 9; ++i) {
if (i != ii && v[i][jj] == k)
return 0;
if (i != jj && v[ii][i] == k)
return 0;
}
//Returns 0 if duplicate found return 1 if no duplicate found.
return 1;
}
void bt()
{
int i,j,k,ok=0;
//Backtracking function recursive
for(i=1;i<=9;i++){
for(j=1;j<=9;j++)
if(v[i][j]==0)
{
ok=1;
break;
}
if(ok)
break;
}
if(!ok)
{
afisare();
return;
}
for(k=1;k<=9;k++)
if(valid(k,i,j))
{
v[i][j]=k;
bt();
}
v[i][j]=0;
}
int main()
{
//Reading from the file the Matrix blank boxes with 0
int i,j;
freopen("sudoku.in","r",stdin);
for(i=1;i<=9;i++)
for(j=1;j<=9;j++)
scanf("%d",&v[i][j]);
bt();
system("pause");
return 0;
}
I know in function Valid I should have the condition to check every 3x3 grid but I don't figure it out: I found those solution to create some variables start and end
and every variable get something like this:
start = i/3*3;
finnish = j/3*3;
i and j in my case are ii and jj.
For example found something like this:
for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
for (int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++)
if (row != i && col != j && grid[row][col] == grid[i][j])
return false;
I tryed this code and it doesn't work.
I don't understand this: I have the next matrix for sudoku:
1-1 1-2 1-3 1-4 1-5 1-6
2-1 2-2 2-3 2-4 2-5 2-6
3-1 3-2 3-3 3-4 3-5 3-6
If my code put's a value on 3-2 how he check in his grid for duplicate value, that formula may work for 1-1 or 3-3 but for middle values doesn't work, understand ?
If my program get's to 2-5 matrix value It should check if this value is duplicate with 1-4 1-5 1-6 2-4 2-6 ... untill 3-6.
Since you are using index arrays starting with 1 and not zero, you have to correct for that when calculating the sub-grid indexes.
start = (i - 1) / 3 * 3 + 1;
finish = (j - 1) / 3 * 3 + 1;

Resources