//3.螺旋矩阵 //例如 n=4 //要求:打印出螺旋矩阵,求 i 行 j 列的数字,0<n<10000 //算法思想:只要找出每一层的第一个数即可,第一个数值为上一层的第一个数+4*n+4,循 //环时 n 每次减 2 //+--------------------------> X 轴 //| 1 2 3 4 // 12 13 14 5 //| 11 16 15 6 //| 10 9 8 7
#include <iostream> using namespace std; void input(int A[100][100],int n,int x,int y) { int a = 0, b = 0, c = 0, d = 0; bool right = true, left = false, up = false, donw = false; for (int i = 0; i < n; i++) { scanf("%d", &A[a][b]); if (b == (y - 1) && right == true) { right = false; donw = true; } else if (a == (x - 1) && b == (y - 1) && donw == true) { left = true; donw = false; } else if (b == d && a == (x - 1) && left == true) { left = false; up = true; c++; } else if (c == a && b == d && up == true) { up = false; right = true; d++; x--; y--; } if (right == true) b++; else if (left == true) b--; else if (up == true) a--; else if (donw == true) a++; } }//非递归调用螺旋输入
void print(int A[100][100],int n,int x,int y) { int a = 0, b = 0, c = 0, d = 0; bool right = true, left = false, up = false, donw = false; for (int i = 0; i < n; i++) { printf("%3d",A[a][b]); if (b == (y - 1) && right == true) { right = false; donw = true; } else if (a == (x - 1) && b == (y - 1) && donw == true) { left = true; donw = false; } else if (b == d && a == (x - 1) && left == true) { left = false; up = true; c++; } else if (c == a && b == d && up == true) { up = false; right = true; d++; x--; y--; } if (right == true) b++; else if (left == true) b--; else if (up == true) a--; else if (donw == true) a++; } }//非递归调用螺旋打印
void Found(int A[100][100],int a,int b,int start,int x,int y) { if (x <= 0||y<=0) return; if (x*y == 1) { A[a][b] = start; return; } for (int i = b; i < b + y - 1; i++)//上部 A[a][i] = start++; for (int j = a; j < a + x - 1; j++)//右边 A[j][b + y - 1] = start++; for (int i = b + y - 1; i > b; i--)//底部 A[a + x - 1][i] = start++; for (int j = a + x - 1; j > a; j--)//左边 A[j][b] = start++; Found(A, a + 1, b + 1, start, x - 2,y-2); }//递归调用螺旋输入 void Print(int A[100][100],int a,int b,int start,int x,int y) { if (x*y <= 0) return; if (x*y == 1) { printf("%3d",A[a][b]); return; } for (int i = b; i < b + y - 1; i++)//上部 printf("%3d",A[a][i]); for (int j = a; j < x + a - 1; j++)//右边 printf("%3d",A[j][y + b - 1]); for (int i = y + b - 1; i > b; i--)//底部 printf("%3d",A[x + a - 1][i]); for (int j = x + a - 1; j > a; j--)//左边 printf("%3d",A[j][b] ); Print(A, a + 1, b + 1, start, x - 2,y-2); }//递归调用螺旋打印
int main() { int A[100][100] = {0}; int x, y, n; scanf("%d%d", &x,&y); n = x * y; input(A,n,x,y);//非递归螺旋矩阵输入 print(A,n,x,y);//非递归螺旋矩阵螺旋打印 // Found(A,0,0,1,x,y);//递归螺旋矩阵输入 // Print(A,0,0,1,x,y);//递归螺旋矩阵打印 printf("\n\n"); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) printf("%5d",A[i][j]);//按行和列正常打印 cout << endl; } }标签:遍历,false,int,矩阵,else,++,二维,&&,true From: https://blog.csdn.net/2401_83795651/article/details/136938676