魔方陣
#include <iostream>
using namespace std;
void main(){
const int ms = 9;
int M[ms][ms];
int i, j;
int r = 0, c = (int) (ms / 2);
for(i = 0; i< ms;i++){
for(j = 0; j< ms;j++){
M[i][j] = 0;
}
}
M[r][c] = 1;
for (int step = 2; step <= ms*ms; step++){
r = (r - 1 + ms) % ms; c = (c -1 + ms) % ms;
if (M[r][c] != 0) {
r = (r + 2) % ms;
c = (c + 1) % ms;
}
M[r][c] = step;
}
for(i = 0; i< ms;i++){
for(j = 0; j< ms;j++){
if (M[i][j] < 10) cout << " ";
cout << M[i][j] << " " ;
}
cout << endl;
}
cin >> i;
}
動態記體配置版本
#include <iostream>
#include "stdio.h"
using namespace std;
int main(void){
int matrixSize ;
cin >> matrixSize;
int** Matrix; //宣告一個"指標的指標",或"陣列的陣列",就是2維陣列
Matrix = (int **)malloc(matrixSize*sizeof(int)); //配置第一維整數陣列
for (int i=0; i<matrixSize; i++){
Matrix[i] = (int *)malloc(matrixSize*sizeof(int)); //配置第2維陣列
}
if (matrixSize%2 == 0 && matrixSize < 3) return -1;
for (int i = 0; i < matrixSize; i++){
for(int j=0; j< matrixSize; j++){
Matrix[i][j] = 0 ; //將陣列裏的每個元素初始為0
}
}
int row =0;
int col = matrixSize / 2;
Matrix[row][col] = 1;
for (int stepper = 2; stepper <= matrixSize * matrixSize; stepper++){
row = (row - 1 + matrixSize) % matrixSize;
col = (col - 1 + matrixSize) % matrixSize;
if (Matrix[row][col] != 0) {
row = (row + 2) % matrixSize;
col = (col + 1) % matrixSize;
}
Matrix[row][col] = stepper;
}
for (int i = 0; i < matrixSize; i++){
for(int j=0; j< matrixSize; j++){
printf("%4d ", Matrix[i][j]) ;
}
cout << endl;
}
}