ccbeginner

ZJ c292

Oct 15th, 2020 (edited)
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. // Judge: https://zerojudge.tw/ShowProblem?problemid=c292
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. /*
  7.     This problem is simple but a little hard to code for beginners.
  8.     For beginners, they may write four or even more 'if' & 'else' to the for directions respectively.
  9.     However, we have a faster, concise, and powerful method by using arrays.
  10.  
  11.     Think about the relative position for representing directions:
  12.     Left, Up, Right, and Down!
  13.     Notice that how I designed the order.
  14.  
  15.     The four directions actualy correspond to what problem says:
  16.         0 -> Left, 1 -> Up, 2 -> Right, 3 -> Down
  17.     Another advantage of this order is that, if your current direction is D, you can do
  18.         'D = (D+1)%4' to turn right,
  19.         'D = (D+3)%4' to turn left.
  20.     See my code below.
  21. */
  22. //direction:L  U   R  D
  23. int dx[] = {0, -1, 0, 1};
  24. int dy[] = {-1, 0, 1, 0};
  25.  
  26. int arr[49][49];// input numbers
  27. bool vis[49][49];// vis[i][j] is 1 when arr[i][j] has been printed
  28.  
  29. int main(){
  30.     // inputs
  31.     int n, dir;
  32.     cin >> n >> dir;
  33.     for(int i = 0; i < n; ++i){
  34.         for(int j = 0; j < n; ++j){
  35.             cin >> arr[i][j];
  36.         }
  37.     }
  38.     --dir;// that way, '(dir+1)%4' in the line 43 will be the corrent direction
  39.     int x = n/2, y = n/2;
  40.     while(0 <= x && x < n && 0 <= y && y < n){// checking boundaries
  41.         cout << arr[x][y];
  42.         vis[x][y] = 1;
  43.         int tryd = (dir+1) % 4;// the right direction
  44.         if(vis[x + dx[tryd]][y + dy[tryd]] == 0){
  45.             // change direction if available
  46.             dir = tryd;
  47.         }
  48.         // move
  49.         x += dx[dir];
  50.         y += dy[dir];
  51.     }
  52.     cout << '\n';
  53.     return 0;
  54. }
Add Comment
Please, Sign In to add comment