打印螺旋队列(更简单的方法)(难度:1颗星)
2017-05-13 00:38
369 查看
输入n*n矩阵的n值,打印出一个螺旋矩阵,如下面例子:
当n= 5时,输出
更简单的方法1:
根据x,y的坐标值,然后通过计算,直接打印对应的值,以中心点建立直角坐标系,这样外面的数字就可以一圈一圈的展开。
参考代码:
更简单的方法2:
通过数组保存4个方向的增量,然后一直沿着某个方向走,只要合法,继续走,不合法则换一个方向继续走,直到全部走完为止。
参考代码:
运行结果:
当n= 5时,输出
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
更简单的方法1:
根据x,y的坐标值,然后通过计算,直接打印对应的值,以中心点建立直角坐标系,这样外面的数字就可以一圈一圈的展开。
参考代码:
#include <stdio.h> #define MAXI(a, b) ((a) > (b) ? (a) : (b)) #define ABSI(a) ((a) > 0 ? (a) : (-a)) int main() { int n, saveSquareN, i, j, maxTwo, nEdge, square; scanf_s("%d", &n); saveSquareN = n * n; n /= 2; for (i = -n; i <= n; i++) { for (j = -n; j <= n; j++) { if (0 == saveSquareN % 2 && (0 == i || 0 == j)) continue; maxTwo = MAXI(ABSI(i), ABSI(j)); nEdge = saveSquareN % 2 ? 2 * maxTwo + 1 : 2 * maxTwo; square = nEdge * nEdge; if (i == maxTwo) square % 2 ? printf("%5d", saveSquareN + 1 - ((2 * square - 5 * (nEdge - 1)) / 2 + j)) : printf("%5d", saveSquareN + 1 - (int)((2 * square - 5 * (nEdge - 1)) / 2.0 + (j > 0 ? j - 0.5 : j + 0.5))); else if (i == -maxTwo) square % 2 ? printf("%5d", saveSquareN + 1 - ((2 * square - (nEdge - 1)) / 2 - j)) : printf("%5d", saveSquareN + 1 - (int)((2 * square - (nEdge - 1)) / 2.0 - (j > 0 ? j - 0.5 : j + 0.5))); else if (j == maxTwo) square % 2 ? printf("%5d", saveSquareN + 1 - ((2 * square - 3 * (nEdge - 1)) / 2 - i)) : printf("%5d", saveSquareN + 1 - (int)((2 * square - 3 * (nEdge - 1)) / 2.0 - (i > 0 ? i - 0.5 : i + 0.5))); else square % 2 ? printf("%5d", saveSquareN + 1 - ((2 * square - 7 * (nEdge - 1)) / 2 + i)) : printf("%5d", saveSquareN + 1 - (int)((2 * square - 7 * (nEdge - 1)) / 2.0 + (i > 0 ? i - 0.5 : i + 0.5))); } if (saveSquareN % 2 || i) printf("\n"); } return 0; }
更简单的方法2:
通过数组保存4个方向的增量,然后一直沿着某个方向走,只要合法,继续走,不合法则换一个方向继续走,直到全部走完为止。
参考代码:
#include <stdio.h> int arr[100][100], n; int dir[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; int IsPosOk(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n && 0 == arr[x][y]; } int main() { int i, j, PosX = 0, PosY = 0, nCount = 1, curDir = 0; scanf_s("%d", &n); arr[0][0] = nCount++; while (nCount <= n * n) { if (IsPosOk(PosX + dir[curDir][0], PosY + dir[curDir][1])) { PosX += dir[curDir][0]; PosY += dir[curDir][1]; arr[PosX][PosY] = nCount++; } else curDir = (curDir + 1) % 4; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("%5d", arr[i][j]); printf("\n"); } return 0; }
运行结果:
相关文章推荐
- 螺旋队列-打印-查找-步数解法-边界解法
- 一个简单的消除调试打印方法
- linux 打印错误的简单方法
- Range类中的三个方法及简单打印
- 螺旋队列的打印
- 最简单打印三角形方法
- java打印菱形的简单方法
- Code Fragment-对于简单的数据类,通过覆盖toString方法,打印关键信息。
- MFC中获取指定打印机的打印队列的方法
- 简单介绍CSS设置打印页面的方法及css里media的使用
- web上的一些简单打印方法
- JS简单方法打印页面指定内容
- 倒序打印的聪明递归方法~当然也可以使用堆栈法和最简单易懂的循环法
- android java 打印调用堆栈的一个简单方法
- POJ 3125 Printer Queue【简单模拟a打印队列】
- 页面打印URL的简单方法比较
- WEB页面开发的简单易用的打印方法
- 打印螺旋队列
- 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
- php 的简单易用的调式方法,打印方法