直接看代码:
//1.初始化数据 int len = 10;//横排的长度 int dic = 0;//4个方向。 int x = 0, y = 0;//当前的位置。 int v = 1;//当前的值 int q = 0;//当前已经画的圈数 int[][] info = new int[len][];//存放数组 string zero = "";//格式化数据 int zl = len * len;//矩阵的大小 for (int i = 0; i < zl.ToString().Length; i++) { zero += "0"; } for (int i = 0; i < info.Length; i++) { info[i] = new int[len]; } //2.赋值 for (int i = 0; i < zl; i++) { switch (dic % 4) { case 0: if (y == len - q - 1) { info[x][y] = v; dic += 1; x += 1; } else { info[x][y] = v; y += 1; } break; case 1: if (x == len - q - 1) { info[x][y] = v; dic += 1; y -= 1; } else { info[x][y] = v; x += 1; } break; case 2: if (y == q) { info[x][y] = v; dic += 1; x -= 1; } else { info[x][y] = v; y -= 1; } break; case 3: if (x == q + 1) { info[x][y] = v; dic += 1; y += 1; q += 1; } else { info[x][y] = v; x -= 1; } break; } v += 1; } //3.打印 for (int i = 0; i < info.Length; i++) { for (int j = 0; j < info[i].Length; j++) { Console.Write(info[i][j].ToString(zero) + " "); } Console.WriteLine(); }
思想是我们小时候的举动:拿只笔在沙子上不停的画圈圈,圈圈越来越小。。。。