-------------------------------------------------------------------------------------------
void MagicSquare(int n)
{ int i, j, k, l, data;
int ** square = new int * [n];
for (i=0; i<n; i++)
{ square[i] = new int [n];
}
for (i=0; i<n; i++)
for (j=0; j<n; j++)
square[i][j]=0;
if (radioButton1->Checked || radioButton3->Checked)
{ i = 0;
j = (n-1)/2;
}
else
{ i = n-1;
j = (n-1)/2;
}
square[i][j] = 1;
data = 2;
while (data <= n*n)
{ if (radioButton1->Checked)
{ k = (i-1<0) ? n-1 : i-1;
l = (j-1<0) ? n-1 : j-1;
if (square[k][l]>0) i = (i+1) % n;
else { i = k; j = l; }
}
else if (radioButton2->Checked)
{ k = (i+1==n) ? 0 : i+1;
l = (j-1<0) ? n-1 : j-1;
if (square[k][l]>0) i = (i-1 < 0) ? n-1 : i-1;
else { i = k; j = l; }
}
else if (radioButton3->Checked)
{ k = (i-1<0) ? n-1 : i-1;
l = (j+1==n) ? 0 : j+1;
if (square[k][l]>0) i = (i+1) % n;
else { i = k; j = l; }
}
else if (radioButton4->Checked)
{ k = (i+1==n) ? 0 : i+1;
l = (j+1==n) ? 0 : j+1;
if (square[k][l]>0) i = (i-1 < 0) ? n-1 : i-1;
else { i = k; j = l; }
}
square[i][j]=data++;
}
}
==================Visual Studio 2022==================================================
private: void print_dataGridView(int** square, int size) {
dataGridView1->RowCount = size;
dataGridView1->ColumnCount = size;
dataGridView1->ColumnHeadersVisible = false;
dataGridView1->RowHeadersVisible = false;
//dataGridView1->AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode::Fill; // 從設計那邊設定
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
dataGridView1->Rows[i]->Cells[j]->Value = square[i][j];
}
}
}
// Magic Square 主程式
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e){
int size = int::Parse(textBox1->Text);
int start_row = 0;
int start_column = (size - 1) / 2; // 從第一列中間開始填上1
int start_number = 1;
int next_row;
int next_column;
int** square;
square = new int*[size];
for (int i = 0; i < size; i++){
square[i] = new int[size];
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
square[i][j] = 0;
}
}
square[start_row][start_column] = start_number;
for (int i = 2; i <= size * size; i++) {
if (radioButton1->Checked == true) { // 往左上陸續填數字
next_row = (start_row - 1 + size) % size;
next_column = (start_column - 1 + size) % size;
if (square[next_row][next_column] == 0) {
square[next_row][next_column] = i;
start_row = next_row;
start_column = next_column;
}else {
start_row = (start_row + 1 + size) % size;
square[start_row][start_column] = i;
}
}
else { // 往右上
next_row = (start_row - 1 + size) % size;
next_column = (start_column + 1 + size) % size;
if (square[next_row][next_column] == 0) {
square[next_row][next_column] = i;
start_row = next_row;
start_column = next_column;
}
else {
start_row = (start_row + 1 + size) % size;
square[start_row][start_column] = i;
}
}
}
print_dataGridView(square, size);
}