knightL

Spiral

Dec 25th, 2021
1,151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <cassert>
  4. #include <string>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. const int MAXN = 101;
  9.  
  10. int a[MAXN][MAXN];
  11. int dx[4] = {0, 1, 0, -1};
  12. int dy[4] = {1, 0, -1, 0};
  13.  
  14. int main()
  15. {
  16.     int n,m;
  17.     scanf("%d%d",&n,&m);
  18.     int x = 0;
  19.     int y = 0;
  20.     int dir = 0;
  21.     int k = 1;
  22.  
  23.     a[0][0] = k;
  24.     k++;
  25.  
  26.     while( k <= n*m )
  27.     {
  28.         int nextX = x + dx[dir];
  29.         int nextY = y + dy[dir];
  30.         if( 0<= nextX && nextX < n && 0<= nextY && nextY < m && a[nextX][nextY] == 0)
  31.         {
  32.             x = nextX;
  33.             y = nextY;
  34.             a[x][y] = k;
  35.             k++;
  36.         }
  37.         else
  38.         {
  39.             dir++;
  40.             if(dir==4)
  41.                 dir=0;
  42.         }
  43.     }
  44.  
  45.     for(int i=0; i<n; i++)
  46.     {
  47.         for(int j=0; j<m; j++)
  48.         {
  49.             if(j!=0)
  50.                 printf(" ");
  51.             printf("%d", a[i][j]);
  52.         }
  53.         printf("\n");
  54.     }
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment