【程式設計-C#】魔方陣
魔方陣的解法/演算法:
設有奇數方陣,3×3, 5×5…, nxn
要將1~nxn的數值填入此方陣中,使得此方陣的各列、各行、斜行/列上的數值加總為相等。
Step 1: 將1置放於方陣的第1列中間位置
設N= 2 … nxn
Step 2: 往左上角找候選的位置來放入N,此時左上角的位置,會有底下2種狀況
狀況1: 左上角的位置跑出陣列外,此時,我們將左上角位置另一端位置做為新候選位置。
狀況2:若候選位置上已經被佔據了(已有數值),此時,我們將原本數值位置的下方位置,做為新候選位置。
Step 3: 將數值N放入候選位置/新候選位置 (找到的可放置數值位置)。
Step 4:N加1,重覆Step 2與Step 4,直到N等於nxn。
if & 取餘數循環版
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void makeMagicMatrix1(int matrixSize) { int[,] Matrix = new int[99, 99]; int row = 0; int col = matrixSize / 2; Matrix[row, col] = 1; for (int stepper = 2; stepper <= matrixSize * matrixSize; stepper++) { row--;col--; //往左上角移動,二維陣列行與列索引皆減1 //判斷是否出界,小於0為出界的條件 if (row < 0) row = matrixSize - 1; if (col < 0) col = matrixSize - 1; if (Matrix[row, col] != 0) //判斷要放置的位處若不是空的話,需要進行倒退的的動作 { row = (row + 2); col = (col + 1); //倒退後,也有可能出界,大於matrixSize-1為出界的條件 if (row >= matrixSize) row = row - matrixSize; if (col >= matrixSize) col = col - matrixSize; } Matrix[row, col] = stepper; } string outStrng = ""; for (int i = 0; i < matrixSize; i++) { for (int j = 0; j < matrixSize; j++) { outStrng += Matrix[i, j].ToString().PadLeft(2, ' ') + " "; } outStrng += "\r\n"; } label2.Text = outStrng; label2.Location = new Point((this.panel2.Width - label2.Width) / 2, 0); //置中label2 } private void makeMagicMatrix2(int matrixSize) { int[,] Matrix = new int[99, 99]; 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; } string outStrng = ""; for (int i = 0; i < matrixSize; i++) { for (int j = 0; j < matrixSize; j++) { outStrng += Matrix[i, j].ToString().PadLeft(2, ' ') + " "; } outStrng += "\r\n"; } label2.Text = outStrng; label2.Location = new Point((this.panel2.Width - label2.Width) / 2, 0); //置中label2 } private void button1_Click(object sender, EventArgs e) { int matrixSize = Convert.ToInt32(textBox1.Text); makeMagicMatrix1(matrixSize); } } }
2018/10/24 程式碼
const int n = 5; int[,] M = new int[n, n]; int row = 0, col = n / 2; M[row, col] = 1; //將1放入第1列中間位置 for (int N = 2; N <= n * n; N++) { //狀況1 row = (row - 1 + n) % n; col = (col - 1 + n) % n; //狀況2 if (M[row, col] != 0) //要放的位置上已經有數值 { row = (row + 2) % n; col = (col + 1) % n; } M[row, col] = N; //將N放入決定好的位置 } //輸出魔方陣 for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { Console.Write("{0, 4}", M[r, c]); } Console.WriteLine(); }