当前位置:网站首页>第一讲:蛇形矩阵
第一讲:蛇形矩阵
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;
}
边栏推荐
- 如何開發引入小程序插件
- Cobaltstrike builds an intranet tunnel
- Technology cloud report: how many hurdles does the computing power network need to cross?
- IIC bus realizes client device
- Oracle triggers
- The new content of the text component can be added through the tag_ Config set foreground and background colors
- The code generator has deoptimised the styling of xx/typescript. js as it exceeds the max of 500kb
- 南京:全面启用商品房买卖电子合同
- How can Bluetooth in notebook computer be used to connect headphones
- Overriding equals() & hashCode() in sub classes … considering super fields
猜你喜欢
IIC bus realizes client device
Qtquick3d real time reflection
Blocking of concurrency control
Server optimization of performance tuning methodology
Distributed resource management and task scheduling framework yarn
50. Pow(x, n). O(logN) Sol
Type of fault
database mirroring
[error record] file search strategy in groovy project (src/main/groovy/script.groovy needs to be used in the main function | groovy script directly uses the relative path of code)
Nacos installation and service registration
随机推荐
a-tree 树的全部展开和收起
[Chongqing Guangdong education] National Open University autumn 2018 0088-21t Insurance Introduction reference questions
[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)
笔记本电脑蓝牙怎么用来连接耳机
MCU case -int0 and INT1 interrupt count
Meituan dynamic thread pool practice ideas, open source
Postman核心功能解析-参数化和测试报告
點到直線的距離直線的交點及夾角
Leetcode simple question: find the nearest point with the same X or Y coordinate
Alternating merging strings of leetcode simple questions
Damn, window in ie open()
Calculation method of boundary IOU
Business learning of mall commodity module
数据泄露怎么办?'华生·K'7招消灭安全威胁
Leetcode simple question check whether all characters appear the same number of times
FBO and RBO disappeared in webgpu
What changes has Web3 brought to the Internet?
Wonderful review of the digital Expo | highlight scientific research strength, and Zhongchuang computing power won the digital influence enterprise award
Comment développer un plug - in d'applet
Recovery technology with checkpoints