3x3 magic square is an NxN matrix in which every row, column, and diagonal add up to the same number.
the algorithm:
Start with the middle entry of the top row. Place a 1 there. Now we'll move consecutively through the other squares and place the numbers 2, 3, 4, etc. It's easy: after placing a number, just remember to always move:
1. diagonally up and to the left when you can,
2. go down if the box is already occupied
The only thing you must remember is to imagine the matrix has "wrap-around", i.e., if you move off one edge of the magic square, you re-enter on the other side.
My only problem is that in my algorithm is the go down if its occupied, its actually going down but it must be in the previous box, not on the next box,
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
|
#include <iostream>
using namespace std;
int main ()
{
int magicsq[3][3];
int i,j,x;
int row=0; //start positon of row
int col=3/2; // and colum
for( i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
magicsq[i][j] = 0; //initialize to 0 your matrix
}
}
magicsq[row][col] = 1; //position to star the counting
for(x=2;x<=3*3;x++)
{
row--;
col--;
if(row<0){
row=row+3;
}
if(col<0){
col=col+3;
}
if (magicsq[row][col]>0){
row++; //i think this is the part of the problem?
}
magicsq[row][col] = x;
}
for( i = 0; i<3;i++){
for(j = 0; j<3;j++)
{
cout<<magicsq[i][j] <<" ";
}
cout<<endl;
}
}
|