标签:
#region 蛇形矩阵 static void SnakeMatrix() { // 我们把它看做是一个回矩阵 Console.WriteLine("请输入矩阵的行数"); int n = Convert.ToInt32(Console.ReadLine()); if ( 1 == n ) { Console.WriteLine(1); } int rand = n >> 1;// n>>1 是圈数 int[,] a = new int[n , n]; int k = 0; int i = 0; int j = 0; for (i = 0; i < rand; ++i ) { // right for (j = i; j < n - i; ++j) { a[i, j] = ++k; } // bottom for (j = i + 1; j < n - i; ++j) { a[j, n - i - 1] = ++k; } //left for (j = n - 2 - i; j >= i; j--) //向左增长 { a[n - 1 - i, j] = ++k; } //top for (j = n - 1 - 1 - i; j > i; j--) //向上增长 { a[j, i] = ++k; } if (0 != n % 2)//判断奇数 { a[n >> 1, n >> 1] = ++k; } } //顺时针 Console.WriteLine("顺时针"); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { Console.Write( " {0,-4} " , a[i,j] ) ; } Console.WriteLine(); } //逆时针 Console.WriteLine("逆时针"); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { Console.Write(" {0,-4} " , a[j, i]); } Console.WriteLine(); } } #endregion
标签:
原文地址:http://www.cnblogs.com/lihonglin2016/p/4307873.html