当前位置:网站首页>第一讲:蛇形矩阵
第一讲:蛇形矩阵
2022-07-05 22:27:00 【奋斗吧!骚年!】
题目:AcWing 756. 蛇形矩阵
输入两个整数 n 和 m,输出一个 n 行 m 列的矩阵,将数字 1 到 n×m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
输入格式
输入共一行,包含两个整数 n 和 m。
输出格式
输出满足要求的矩阵。
矩阵占 n 行,每行包含 m 个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
题目分析:
这道题主要使用x、y的偏移量
比如(x,y)如果想往下走那么就是(x+1,y+0),其它方向同理
如果换方向?
使用数组保存四个方向的偏移量,如果换方向数组下标+1模4即可。
#include <iostream>
using namespace std;
const int N = 105;
int a[N][N];
int dx[]={
0,1,0,-1}; // 右下左上
int dy[]={
1,0,-1,0};
int main()
{
int n,m;
cin>>n>>m;
int x=0,y=0,d=0;
for(int i=1;i<=n*m;i++)
{
a[x][y]=i;
x+=dx[d],y+=dy[d]; // 进行移动
if(x<0||y<0||x>=n||y>=m||a[x][y])
{
x-=dx[d],y-=dy[d]; //如果移动失败需要恢复原状
d=(d+1)%4;
x+=dx[d],y+=dy[d]; // 再次移动
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)cout<<a[i][j]<<' ';
cout<<endl;
}
return 0;
}
边栏推荐
- U盘的文件无法删除文件怎么办?Win11无法删除U盘文件解决教程
- [groovy] mop meta object protocol and meta programming (Introduction to groovyobject interface | introduction to metaclass | implementation of class methods using groovyobject invokemethod)
- MySQL服务莫名宕机的解决方案
- [agc009e] eternal average - conclusion, DP
- 解决thinkphp启动时“No input file specified”的问题
- 2022软件测试工程师涨薪攻略,3年如何达到30K
- How to quickly experience oneos
- Golang writes the opening chapter of selenium framework
- 科技云报道荣膺全球云计算大会“云鼎奖”2013-2022十周年特别贡献奖
- Alternating merging strings of leetcode simple questions
猜你喜欢

Nacos installation and service registration

How can Bluetooth in notebook computer be used to connect headphones

Performance monitoring of database tuning solutions

Business learning of mall order module

Damn, window in ie open()

Recovery technology with checkpoints

Advantages and disadvantages of the "Chris Richardson microservice series" microservice architecture

Practice: fabric user certificate revocation operation process

点到直线的距离直线的交点及夹角

BFC block level formatting context
随机推荐
Platformio create libopencm3 + FreeRTOS project
Damn, window in ie open()
MySQL actual combat 45 lecture learning (I)
Granularity of blocking of concurrency control
Solutions for unexplained downtime of MySQL services
Learning of mall permission module
Database tuning solution
Concurrency control of performance tuning methodology
Go语言学习教程(十五)
Sentinel production environment practice (I)
Calculation method of boundary IOU
Pinctrl subsystem and GPIO subsystem
119. Pascal‘s Triangle II. Sol
Distance entre les points et les lignes
2022-07-05:给定一个数组,想随时查询任何范围上的最大值。 如果只是根据初始数组建立、并且以后没有修改, 那么RMQ方法比线段树方法好实现,时间复杂度O(N*logN),额外空间复杂度O(N*
ESP32 hosted
MySQL服务莫名宕机的解决方案
Lightweight dynamic monitorable thread pool based on configuration center - dynamictp
二叉树(二)——堆的代码实现
Character conversion PTA