- using System;
- namespace MagicMatrix
- {
- class CRunMain
- {
- public static int Main()
- {
- int nWidth = 0;
- CPrintMatrix objMat;
- Console.WriteLine("please input maxtrix width: ");
- nWidth = int.Parse(Console.ReadLine());
- objMat = new CPrintMatrix(nWidth);
- objMat.PrintMaxtrix();
- return 0;
- }
- };
- class CPrintMatrix
- {
- private int m_nWidth = 0;
- private int [ ,] m_arrMatrix;
- public CPrintMatrix(int nWidth)
- {
- this.m_nWidth = nWidth;
- }
- public void SetWidth(int nWdith)
- {
- this.m_nWidth = nWdith;
- }
- public void PrintMaxtrix()
- {
- int i = 0;
- int j = 0;
- if (!this.SettMatrix())
- {
- return;
- }
- for (i = 0; i < this.m_nWidth; i++)
- {
- for (j = 0; j < this.m_nWidth; j++)
- {
- Console.Write("{0}/t", this.m_arrMatrix[i, j]);
- }
- Console.WriteLine();
- }
- }
- public bool SettMatrix()
- {
- int i = 0;
- int j = 0;
- int k = 0;
- int ii = 0;
- int jj = 0;
- if (0 >= this.m_nWidth)
- {
- Console.WriteLine("width must above 0!current value is {0}", this.m_nWidth);
- return false;
- }
- if (this.m_nWidth % 2 == 0)
- {
- Console.WriteLine("width must odd number! current value is {0}", this.m_nWidth);
- return false;
- }
- //new matricx
- this.m_arrMatrix = new int[this.m_nWidth, this.m_nWidth];
- //init matrix
- for (i = 0; i < this.m_nWidth; i++)
- {
- for (j = 0; j < this.m_nWidth; j++)
- {
- this.m_arrMatrix[i, j] = 0;
- }
- }
- //set value
- this.m_arrMatrix[0, this.m_nWidth/2] = 1;
- i = 0;
- j = this.m_nWidth / 2;
- for (k = 1; k < this.m_nWidth * this.m_nWidth; k++)
- {
- if ( (0 == i) && (0 == j) )
- {
- this.m_arrMatrix[1, 0] = k + 1;
- i = 1;
- j = 0;
- continue;
- }
- ii = (i + this.m_nWidth - 1) % this.m_nWidth;
- jj = (j + this.m_nWidth - 1) % this.m_nWidth;
- if (0 == this.m_arrMatrix[ii, jj])
- {
- this.m_arrMatrix[ii, jj] = k + 1;
- i = ii;
- j = jj;
- }
- else
- {
- ii = (i + 1) % this.m_nWidth;
- jj = j;
- this.m_arrMatrix[ii, jj] = k + 1;
- i = ii;
- j = jj;
- }
- }
- return true;
- }
- };
- }
打印魔方(幻方、九宫图)C#源码
最新推荐文章于 2021-05-19 16:02:45 发布