P5731 【深基5.习6】蛇形方阵

题目链接:https://www.luogu.com.cn/problem/P5731

解题思路:

  其实之前做过同样的题目,只不过今天再做的时候,竟然没有秒过,还是基础不扎实,复习一下。

  方法一:dfs,控制移动的方向,以及把每次拐弯时的那个越界的点再掰回。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int a[210][210];
 4 bool vis[210][210];
 5 int n;
 6 int t = 1;
 7 void dfs(int x, int y, int dx, int dy) {
 8     if (x < 1 || y < 1 || x > n || y > n || vis[x][y] == true) {
 9         return;
10     } 
11     while (x >= 1 && y >= 1 && x <= n && y <= n && vis[x][y] == false) {
12         a[x][y] = t++;
13         vis[x][y] = true;
14         x += dx;
15         y += dy;
16     }
17     if (dx == 1 && dy == 0) { //
18         dfs(x - 1, y - 1, 0, -1); //变为向左
19     } else if (dx == 0 && dy == 1) { //
20         dfs(x + 1, y - 1, 1, 0); //变为向下
21     } else if (dx == -1 && dy == 0) { //
22         dfs(x + 1, y + 1, 0, 1); //变为向右
23     } else if (dx == 0 && dy == -1) { //
24         dfs(x - 1, y + 1, -1, 0); //变为向上
25     }
26 }
27 int main() {
28     cin >> n;
29     dfs(1, 1, 0, 1);
30     for (int i = 1; i <= n; i++) {
31         for (int j = 1; j <= n; j++) {
32             printf("%3d", a[i][j]);
33         }
34         printf("\n");
35     }
36     return 0; 
37 } 

   解法二:常规思路,四个while循环

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int a[15][15];
 4 int main() {
 5     int n;
 6     scanf("%d", &n);
 7     int k = 1;
 8     int x = 1, y = 0;
 9     int sum = n * n;
10     while (k <= sum) {
11         while (y < n && !a[x][y + 1]) { //
12             a[x][++y] = k++;
13         }
14         while (x < n && !a[x + 1][y]) { //
15             a[++x][y] = k++;
16         }
17         while (y > 1 && !a[x][y - 1]) { //
18             a[x][--y] = k++;
19         }
20         while (x > 1 && !a[x - 1][y]) { //
21             a[--x][y] = k++;
22         }
23     }
24     for (int i = 1; i <= n; i++) {
25         for (int j = 1; j <= n; j++) {
26             printf("%3d",a[i][j]);
27         }
28         printf("\n");    
29     }    
30     return 0;
31 }

 

posted @ 2020-09-24 18:47  kyk333  阅读(667)  评论(0)    收藏  举报