• 종료 위치부터 시작 지점으로 찾아가기
  • simulation
  • 상으로 이동하면서 좌우를 확인하여 길이 존재하면 그 길로 이동
  • 좌우로 이동하다 막다른 길이면 상으로 올라가면 된다.
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>

using namespace std;

#define MAX_N 105

int N = 100;
int res;
bool isVisited[MAX_N][2];
int board[MAX_N][MAX_N];
int sr, sc;

int dx[4] = { -1, 0, 1,  0};
int dy[4] = {  0, 1, 0, -1};

void init() {
	memset(board, 0, sizeof(board));
	res = -1;

	int tmp;
	scanf("%d", &tmp);
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++) {
			scanf("%d", &board[i][j]);
			if (board[i][j] == 2) {
				sr = i; sc = j;
			}
		}
}

void solution() {
	int dir = 0;
	int r = sr;
	int c = sc;
	while(true) {
		int ndir = dir;
		switch(dir) {
			case 0:
				if (r == 0) {
					res = c;
					return;
				}

				for (int i = 1; i < 4; i++) {
					if (i == 2) continue;

					int nr = r + dx[i];
					int nc = c + dy[i];
					if \(nr < 0 \|| nr >= N \|| nc < 0 \|| nc >= N)
						continue;
					if (board[nr][nc] == 1) {
						dir = i;
						break;
					}
				}
				break;
			case 1: 
			case 3: 
				int nr = r + dx[dir];
				int nc = c + dy[dir];
				if \(nr < 0 \|| nr >= N \|| nc < 0 \|| nc >= N \|| board\[nr]\[nc] == 0) {
					dir = 0;
				}
				break;
		}
		r += dx[dir];
		c += dy[dir];
	}
}

int main() {
	int testcase = 10;
	for (tc = 1; tc <= testcase; tc++) {
		init();
		solution();
		printf("#%d %d\n", tc, res);
	}
}