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
36
37
38
39
40
41
42
43
|
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 150;
int a[maxn][maxn];
int main()
{
int n, m;
cin >> n >> m;
memset(a, 0, sizeof(a));
int x = 0, y = 0; //初始坐标坐标,(0,0)
int cnt = 1; //初始化第一个数
a[x][y] = cnt;
while (cnt < n * m )
{
//用下一笔的位置来判断
//向右, 符合条件,则填入下一笔。____提前预判
while (y + 1 < m && !a[x][y + 1]) a[x][ ++ y] = ++ cnt;
//向下
while (x + 1 < n && !a[x + 1][y]) a[ ++ x][y] = ++ cnt;
//向左
while (y - 1 >= 0 && !a[x][y - 1]) a[x][ -- y] = ++ cnt;
//向上
while (x - 1 >= 0 && !a[x - 1][y]) a[ -- x][y] = ++ cnt;
}
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < m; j ++ )
{
cout << a[i][j] << " ";
// printf("%-5d", a[i][j]);
}
cout << endl;
}
return 0;
}
|