Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Judge: https://zerojudge.tw/ShowProblem?problemid=c292
- #include <bits/stdc++.h>
- using namespace std;
- /*
- This problem is simple but a little hard to code for beginners.
- For beginners, they may write four or even more 'if' & 'else' to the for directions respectively.
- However, we have a faster, concise, and powerful method by using arrays.
- Think about the relative position for representing directions:
- Left, Up, Right, and Down!
- Notice that how I designed the order.
- The four directions actualy correspond to what problem says:
- 0 -> Left, 1 -> Up, 2 -> Right, 3 -> Down
- Another advantage of this order is that, if your current direction is D, you can do
- 'D = (D+1)%4' to turn right,
- 'D = (D+3)%4' to turn left.
- See my code below.
- */
- //direction:L U R D
- int dx[] = {0, -1, 0, 1};
- int dy[] = {-1, 0, 1, 0};
- int arr[49][49];// input numbers
- bool vis[49][49];// vis[i][j] is 1 when arr[i][j] has been printed
- int main(){
- // inputs
- int n, dir;
- cin >> n >> dir;
- for(int i = 0; i < n; ++i){
- for(int j = 0; j < n; ++j){
- cin >> arr[i][j];
- }
- }
- --dir;// that way, '(dir+1)%4' in the line 43 will be the corrent direction
- int x = n/2, y = n/2;
- while(0 <= x && x < n && 0 <= y && y < n){// checking boundaries
- cout << arr[x][y];
- vis[x][y] = 1;
- int tryd = (dir+1) % 4;// the right direction
- if(vis[x + dx[tryd]][y + dy[tryd]] == 0){
- // change direction if available
- dir = tryd;
- }
- // move
- x += dx[dir];
- y += dy[dir];
- }
- cout << '\n';
- return 0;
- }
Add Comment
Please, Sign In to add comment