Sudoku: checking 3x3 grids for repeating values - c

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;

Related

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.

Printing a Diamond of Numbers in C

int print_pattern(){
int x;
int y;
int i;
//for loop for the bottom and the top, 0 is the top and 1 is the bottom while it stops at anything above 2.
for (i = 0; i<2;i++){
//loop to the current number
for (x=1;x<=input;x+=2){
// top or bottom, this is the top because i had made the top of the diamond the 0
// therefore this makes my diamond print the top of the function.
if ( i == 0){
//starts for the top of the diamond. and counts the spaces.
for (y=1; y<=input-x; y++){
printf(" ");
}
//starts the printing of the diamond.
for (y=1; y<2*x;y++){
printf("%d ", y);
}
}
//bottom of the diamond, which is from the 1. For this spot it take in the one from the for loop to
// this if statement.
if (i==1){
//counting spaces again
for(y = 1; y<=x; y++){
printf(" ");
}
//printing again but this is the bottom of the pyramid. #really need to comment more
for(y = 1; y<(input-x)*2;y++){
printf("%d ", y);
}
}
//next line starts when printing out the numbers in the output.
printf("\n");
}
}
}
The output is supposed to look like a diamond of the numbers ending with the odd numberat each row. but it is going +2 number past the input and then also not printing the last line. Which should have a single one.
1 1
1 2 3 1 2 3 4 5
1 2 3 4 5 1 2 3 4 5 6 7 8 9
1 2 3 1 2 3 4 5 6 7
1 1 2 3
The left is what is expected and the right is what I currently am getting when inputting 5.
Because you already increment x by 2 in the upper part, you don't need to let the print loop run to y<2*x. It should probably just run to x.
The print loop in the lower part suffers from the fact that y<(input-x)*2 should probably be y<input-x*2 (you want to print 2 less each time).
Generally I'd try to name variables in a more speaking way, like printStartPosition, maxNumToPrint, stuff like that. That makes it easier by a surprising margin to understand a program.
As an enhancement, the two code blocks depending on the i value inside the x loop are structurally very similar. One could try to exploit that and collapse both of them into a function which gets a boolean parameter like "ascending", which increments y when true and decrements it when false. Whether that improves or hinders readability would have to be seen.
Also, keep your variables local if possible.
Peter Schneider has already raised some valid points in his answer.
Think about what you have to do when you print a diamond of height 5:
print 1 centered;
print 1 2 3 centered;
print 1 2 3 4 5 centered;
print 1 2 3 centered;
print 1 centered.
Sou you could write a function that prints the numbers from 1 to n centered in a line and call it with n = 1, 3, 5, 3, 1. This can be achieved with two independent loops, one incrementing n by 2, the other decrementing it.
Another approach is to recurse: print the lines as you go deeper, incrementing n by 2 until you reach the target width, at which point you don't recurse, but return and print lines with the same parameters again as you go up. This will print each line twice except the middle one.
Here's a recursive solution:
#include <stdlib.h>
#include <stdio.h>
void print_line(int i, int n)
{
int j;
for (j = i; j < n; j++) putchar(' ');
for (j = 0; j < i; j++) printf("%d ", (j + 1) % 10);
putchar('\n');
}
void print_pattern_r(int i, int n)
{
print_line(i, n); // print top as you go deeper
if (i < n) {
print_pattern_r(i + 2, n); // go deeper
print_line(i, n); // print bottom as you return
}
}
void print_pattern(int n)
{
if (n % 2 == 0) n++; // enforce odd number
print_pattern_r(1, n); // call recursive corefunction
}
int main(int argc, char **argv)
{
int n = 0;
if (argc > 1) n = atoi(argv[1]); // read height from args, if any
if (n <= 0) n = 5; // default: 5
print_pattern(n);
return 0;
}
A JAVA STAR PATTERN PROGRAM FOR DIAMOND SHAPE converted to C Program. Code comment will explain the changes and flow.
#include <stdio.h>
#include <string.h>
void myprintf(const char* a) {
static int iCount = 0;
if (strcmp(a, "\n") == 0) {
iCount = 0; //if it is new line than reset the iCount
printf("\n"); //And print new line
} else
printf(" %d", ++iCount); //Print the value
}
void main() {
int i, j, m;
int num = 5; //Enter odd number
for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
for (j = num; j >= i; j--)
printf(" ");
for (m = 1; m <= i; m++)
myprintf(" *"); //display of star converted to number
myprintf("\n");
}
num -= 2; //Skip to generate the middle row twice
for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
printf(" ");
for (j = 1; j <= i; j++)
printf(" ");
for (m = num; m >= i; m--)
myprintf(" *"); //display of star converted to number
myprintf("\n");
}
}
Output:
1
1 2 3
1 2 3 4 5
1 2 3
1
Here's the short code for such a diamond.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int w = 9;
int l;
for(l=0; l < w; ++l)
{
printf("%*.*s\n", abs(w/2 - l)+abs((2*l+1)-(2*l+1>w)*2*w), abs((2*l+1)-(2*l+1>w)*2*w), "123456789");
}
return 0;
}

Delete a column and a row in a square matrix in C

I had a square matrix typed dynamically, correctly allocated
double **matrix;
I want to delete a "x" row and "x" column from that matrix, in a way like that:
SOURCE MATRIX:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
I want to remove, for example, the 2nd row/column. The output had to be like this:
FINAL MATRIX:
1 3 4
9 11 12
13 15 16
I've tried to write down and test many algorithms, without success.
How can I do?
Well, to do this, you'll have to realise that in memory your matrix is actually a list of lists.
This means that removing a column is slightly different from removing a row:
Assuming your syntax is matrix[row][column];
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
//TODO check for empty matrix etc;
for(int i=0;i<MATRIX_HEIGHT; i++)
{
while(col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][col]=matrix[i][col+1];
col++;
}
matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT);
}
void removeRow(int** matrix, int row){
MATRIX_HEIGHT--;
//TODO check for empty matrix etc.
free(matrix[row]);
while(row<MATRIX_HEIGHT)
{
//move data up
matrix[row] = matrix[row+1];
row++;
}
}
so removeColumn iterates over each row, and deletes the appropriate item, and removeRow can just free the row, and overwrite its pointer.
NOTE that you have to keep track of the size of the matrix size yourself. In the example i used MATRIX_WIDTH and MATRIX_HEIGHT but you'll have to implement something for this. (Maybe a struct with width height and pointer in it.)
As I was looking for a answer to the similar problem but with matrix stored in linear space here's my solution (I'm using column-major order here, but if you're using row-major it only minor changes are needed)
void removeRow(float * arrayToRemove, const int & currentRows, const int & currentCols, const int & row)
{
auto currDiff = 0;
auto step = currentRows;
auto elemNum = currentRows * currentCols;
for (int i = row, stepCounter = 0; i < elemNum; ++i, ++stepCounter)
{
if (stepCounter % step == 0)
{
++currDiff;
}
else
{
arrayToRemove[i - currDiff] = arrayToRemove[i];
}
}
}
void removeCol(float * arrayToRemove, const int & currentRows, const int & currentCols, const int & col)
{
auto destination = arrayToRemove + (col * currentRows);
auto source = arrayToRemove + ((col + 1) * currentRows);
const auto elemsNum = (currentCols - (col + 1)) * currentRows;
memcpy(destination, source, elemsNum * sizeof(float));
}
What I would do is split this matrix into 5 zones.
1) zone to be deleted. 2) Zone "before" the deleted index (it would be just 1 in your example matrix). 3) Zone "after" the deleted index (it would be 11,12,15,16 in your matrix). 4) and 5) Are the two remaining 'zones'. One would be (3, 4) the other would (9,13)
Just make a conditional for each of the 5 zones and copy.
double** matrix = (double**)malloc(sizeof(double)*n*n);
//fill in the matrix here
double** copy (double**)malloc(sizeof(double)*(n-1)*(n-1));
int i;
int j;
int deleteNum; //what ever row you want to delete
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
if(i < deleteNum && j < deleteNum){
copy[i][j] = matrix[i][j];
}
else if(deleteNum == i || deleteNum == j){
//one of the rows/columns to be deletd
//basically skip
}
else if(i < deleteNum && j > deleteNum){
copy[i][j-1] = matrix[i][j];
}
else if(i > deleteNum && j < deleteNum){
copy[i-1][j] = matrix[i][j]
}
else{
copy[i-1][j-1] = matrix[i][j];
}
}
}

Wrong output with the N Queen

So I have to do a modified version of the N queen problem, where we are given an initial configuration of the chess board filled with pawns, and we need to find the maximum number of queens we can have so that they don't attack each other. The input consists of an integer in the first line giving the dimension of the board ( NxN) and n lines defining the setup of the chess board.The characters will be either a ā€˜pā€™ (meaning there is already a pawn in that location) or an ā€˜eā€™ (meaning that location is empty).
For example, for this input,
5
epepe
ppppp
epepe
ppppp
epepe
the output will be 9.
Here is my code, everything seems clear, but I don't see why it doesnt give the correct output
#include <stdio.h>
#include <malloc.h>
/* function headers */
void do_case(int);
int solve(char **,int,int);
int canPlace(char **,int,int,int);
/* Global vars */
int queens;
int main(void)
{
int n;
scanf("%d",&n);
getchar();
while( n != 0 )
{
do_case(n);
scanf("%d",&n);
getchar();
}
return 0;
}
void do_case(int n)
{
int i,j; //counters for input
//board configuration allocation
char **configuration = (char **)malloc(n*sizeof(char *));
for(i = 0 ; i < n ;i++ )
configuration[i] =(char *)malloc(n*sizeof(char));
queens = 0;
//get input
for( i = 0; i < n; i++ )
{
for( j = 0; j < n; j++ )
{
scanf("%c",&configuration[i][j]);
}
getchar();
}
//solve
solve(configuration,n,0);
printf("%d \n",queens);
}
//recursive solver
int solve(char **configuration,int N,int col)
{
int i,j;
//base case
if( col >= N )
return 1;
//consider this column
//try placing queen in non blocked spot in all rows
for(i = 0; i < N; i++)
{
if ( configuration[i][col] == 'e' && canPlace(configuration,N,i,col) )
{
//Place queen in configuration[i][col]
configuration[i][col] = 'q';
queens++;
//recursion on the rest
if( solve(configuration,N,col + 1) == 1 )
{
return 1;
}
//backtrack
configuration[i][col] = 'e';
queens--;
}
}
return 0;
}
//this function check if queen can be placed
int canPlace(char **configuration,int N, int row, int col)
{
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
{
if (configuration[row][i] == 'q')
{
return 0;
}
}
/* Check upper diagonal on left side */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if ( configuration[i][j] == 'q')
{
return 0;
}
}
/* Check lower diagonal on left side */
for (i = row, j = col; j >= 0 && i < N; i++, j--)
{
if (configuration[i][j] == 'q')
{
return 0;
}
}
return 1;
}
Basically, your code outputs 0 because it requires that we place exactly one queen in every column, which is not the case in your example.
That said, there are multiple problems with the algorithm (and I don't claim the list is complete, though it may be):
The code does not consider every possibility: it will only find the first possible arrangement, and then quit searching after a single "if( col >= N ) return 1;". Instead, it should go like "if( col >= N ) update the best possible value of queens in a separate variable, then return 0 to continue searching".
In the line "if( solve(configuration,N,col + 1) == 1 )", the code assumes there can not be two queens in a single column. The call should use col instead of col + 1, and somehow account for where we stopped at the current column.
To allow columns without queens, an unconditional call to "solve(configuration,N,col + 1)" should be placed somewhere in the solve function.
When we allow item 2, the function canPlace should be modified to also check the column.
The loops of canPlace should break whenever a pawn is found.
With pawns blocking the way, you shouldn't just move on to the next column because you can place more queens in the same column. You should modify your code to pass both a row and a column when you recurse, and only move to the next square, not the next column.
Also, it looks like your algorithm finds the first solution instead of the best solution. The original queens problem only cared about 1 possible solution, but with the modified problem, you need to make sure you check all solutions and remember the best one.
Also, your canPlace function is wrong. It doesn't account for pawns at all.

(C Program) User made magic square fails on 11x11 array but works on every size up to 11x11?

Alright so I thought my code was working and it seems to do so, it allows the user to choose the size of a magic square where the number one is the start point and starts in the center of the first row. The pattern goes along this line....go up one and over one, if you go up above the first row.....move back to the last row or if you run off the end of the right side of the column than go back to the start of the column...in a magic square if your not familiar with it, all sides are equal when the numbers on that side or diagonal are counted.
An odd number must be entered for this to be written out as a magic square (example: 3x3, 5x5, 7x7, etc..) the problem is it works until I enter 11x11....when done, it comes back around and when the program runs into a slot that has already been filled it is supposed to enter the next number below the last one that was entered into the array...but when 11x11 is entered it overwrites the 1 with a 13 which breaks the cycle and ruins the pattern....I would appreciate it if someone helped me with this, I think maybe the problem has to do with the equation I use to choose the starting point. This works all the way up to 11x11, every odd number entered after that seems to overwrite the starting point.
// Chapter 8 Programming Project #17
#include <stdio.h>
#define N_squared (N * N)
#define MOVE (--row, ++column)
#define RW_SIZE ((int) (sizeof(magic_square) / sizeof(magic_square[0])))
void create_magic_square(int N, int magic_square[N][N], int ROW_SIZE);
void print_magic_square(int N, int magic_square[N][N], int ROW_SIZE);
int main(void)
{
int N, row, column;
printf("This program creates a magic square of a specified size\n");
printf("The size must be an odd number between 1 and 99.\n");
printf("Enter size of magic square: ");
scanf("%d", &N);
int magic_square[N][N];
for (row = 0; row < N; row++) {
for (column = 0; column < N; column++) {
magic_square[row][column] = 0;
}
}
// Create magic square
create_magic_square(N, magic_square, RW_SIZE);
// Print magic square
print_magic_square(N, magic_square, RW_SIZE);
return 0;
}
void create_magic_square(int N, int magic_square[N][N], int ROW_SIZE)
{
printf("Size of N*N = %d\nSize of ROW_SIZE = %d\n", N_squared, ROW_SIZE);
// Here I iterate through the numbers, rows, and columns
int i = 1, row = 0;
int column = (((ROW_SIZE + 1) / 2) - 1);
while (i != N_squared + 1){
// if new position is empty place next number
if (magic_square[row][column] == 0) {
magic_square[row][column] = i;
i++;
// If new position is filled then move back and down
} else if (row + 2 < ROW_SIZE &&
column - 1 >= 0) {
row += 2;
column -= 1;
} else if (row + 2 > ROW_SIZE - 1 &&
column - 1 < 0) {
row = 1;
column = ROW_SIZE - 1;
}
// If current position has been set then move
if (magic_square[row][column] != 0)
MOVE;
// If row runs off the board reset
if (row < 0)
row = ROW_SIZE - 1;
// if column runs off the board reset
if (column > ROW_SIZE - 1)
column = 0;
}
}
void print_magic_square(int N, int magic_square[N][N], int ROW_SIZE)
{
int row, column;
printf("\n");
for (row = 0; row < ROW_SIZE; row++) {
for (column = 0; column < ROW_SIZE; column++) {
if (N > 9)
printf(" %3d ", magic_square[row][column]);
else
printf(" %2d ", magic_square[row][column]);
}
printf("\n\n");
}
}

Resources