不用数组打印蛇形矩阵

本文介绍了一种用于打印蛇形矩阵的算法实现。通过定义斜行数字个数、书写顺序等辅助函数,能够准确地计算出指定大小的矩阵中每个位置上的数值,并按蛇形路径打印整个矩阵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

//下标和为s的斜行数字个数
int numof_each(int s,int n){return (s)<=n-1?(s+1):((n<<1)-s-1);}

//x,y所在斜行的数字书写顺序,1表示由下往上,0表示由下往上
int direction(int x,int y) {return (x+y)&1;}

//得到x,y所在斜行第一个被书写的下标(x0,y0)
void get_bound(int x,int y,int n,int &x0,int &y0)
{
int d = direction(x,y);
x0=(d?n-1:0);int step=(d?-1:1);
for(;x0>=0&&x0<=n-1;x0+=step)
{
y0=x+y-x0;
if(y0>=0 && y0<=n-1)break;
}
}

//获取(x,y)被填写的数字
int valueof(int x,int y,int n)
{
int x0,y0;
get_bound(x,y,n,x0,y0);

int v=0;
for(int i=0; i<x0+y0;i++)
v+=numof_each(i,n);
v++;
return v+abs(x-x0);
}

//打印大小为n的蛇形矩阵
void print_snake(int n)
{
   for(int i =  0; i < n; i++)
   {
      for(int j=0; j< n; j++)
          {
         printf("%4d ",valueof(i,j,n));
          }

          printf("/n");
   }
}
void main()
{
int n = 0;
while(true)
{
       scanf("%d",&n);
           if(n<=0)break;
           //getchar();
           print_snake(n);
}

getchar();
}

### C++ 实现打印蛇形矩阵 蛇形矩阵(螺旋矩阵)是一种以螺旋形式填充元素的特殊二维数组布局方式[^1]。下面展示了一个完整的C++程序来生成并打印给定大小 `n` 的蛇形矩阵。 #### 完整代码示例 ```cpp #include <iostream> using namespace std; void generateSpiralMatrix(int n) { int matrix[n][n]; int num = 1; int topRow = 0, bottomRow = n - 1; int leftCol = 0, rightCol = n - 1; while (topRow <= bottomRow && leftCol <= rightCol) { // Fill the top row from left to right. for (int col = leftCol; col <= rightCol; ++col) { matrix[topRow][col] = num++; } topRow++; // Fill the right column from top to bottom. for (int row = topRow; row <= bottomRow; ++row) { matrix[row][rightCol] = num++; } rightCol--; // Fill the bottom row from right to left. if (topRow <= bottomRow) { for (int col = rightCol; col >= leftCol; --col) { matrix[bottomRow][col] = num++; } bottomRow--; } // Fill the left column from bottom to top. if (leftCol <= rightCol) { for (int row = bottomRow; row >= topRow; --row) { matrix[row][leftCol] = num++; } leftCol++; } } // Print the generated spiral matrix. for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << matrix[i][j] << "\t"; } cout << endl; } } int main() { int size; cin >> size; generateSpiralMatrix(size); return 0; } ``` 此代码实现了基于输入参数 `n` 来创建一个 `n×n` 大小的蛇形矩阵,并按指定顺序填充数值,最后逐行输出整个矩阵的内容。该方法考虑到了四个方向上的移动:向右、向下、向左和向上,在每次完成一圈后调整边界直到遍历完整个方阵[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值