蛇形矩阵WriteUp

题目:

题目链接:756. 蛇形矩阵 - AcWing题库

image-20210114153741954

YXC源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

const int N = 110;

int n, m;
int q[N][N];

int main()
{
cin >> n >> m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for (int i = 1; i <= n * m; i ++ )
{
q[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 a >= n b < 0 b >= m q[a][b])
{
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}

for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < m; j ++ )
cout << q[i][j] << ' ';
cout << endl;
}

return 0;
}

Lxxx AC源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int main()
{
int m,n,x = 0,y = 0,d = 1;
const int N = 110;
int f[N][N];
int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
cin >> n >> m;

for(int i=1; i <= m*n; i++){
f[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if(a < 0a >= nb < 0b >= mf[a][b] != 0){
d = (d+1)%4;
a = x + dx[d];
b = y + dy[d];
}
x = a,y = b;
}

for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cout << f[i][j] << ' ';
}
cout << endl;
}

return 0;
}

题目思路:

首先,还是IO坐标系,这很关键!!!

1400fe427a9c3540

背景知识:

image-20210114193753757

题目是关于蛇形矩阵,假象从(0,0)点开始,先向右走,撞墙之后再向下,在撞墙之后再向左……以此类推。

image-20210114195104526

然后再设置下一个方向坐标为(a,b),并实时判断是否撞墙或者该坐标已经被占用。

image-20210114195558797

注意点:

image-20210114200321495

参考文章: