포스트

[SWEA] 1953번: [모의 SW 역량테스트] 탈주범 검거 (Unrated) - C++ 풀이

[SWEA] 1953번: [모의 SW 역량테스트] 탈주범 검거 (Unrated) - C++ 풀이

문제 링크

코드 (C++)

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<queue>
#include<cstring>

using namespace std;

struct pos
{
	int y, x;
};
pos vect[4]{ // 상하좌우
	{-1,0}, {1,0},{0,-1},{0,1}
}; 

pos pipe[8][4] = {
	{},
	{ {1,0},{-1,0},{0,1},{0,-1} },	//1. 상하좌우
	{ {1,0},{-1,0} },				//2
	{ {0,1},{0,-1} },				//3
	{ {-1,0},{0,1} },				//4
	{ {1,0},{0,1} },				//5
	{ {1,0},{0,-1} },				//6
	{ {-1,0},{0,-1} }				//7
};
int pLen[8] = {0,4,2,2,2,2,2,2};
int map[50][50];
int dist[50][50];
int N, M, R, C, L;

bool connect(pos s, pos e) {
	int sId = map[s.y][s.x];
	int eId = map[e.y][e.x];
	bool sCon=false, eCon=false;
	for (int i = 0; i < pLen[sId]; i++)
	{
		if (s.y + pipe[sId][i].y == e.y && s.x + pipe[sId][i].x == e.x)
			sCon = true;
	}
	for (int i = 0; i < pLen[eId]; i++)
	{
		if (e.y + pipe[eId][i].y == s.y && e.x + pipe[eId][i].x == s.x)
			eCon = true;
	}

	if (sCon && eCon) return true;
	else return false;
}


int bfs(pos st, int limit) {
	queue<pos> q;
	q.push(st);
	dist[st.y][st.x] = 1;
	int cnt = 1;
	while (!q.empty())
	{
		pos s = q.front();
		q.pop();
		if (dist[s.y][s.x] == limit)
			break;
		for (int i = 0; i < 4; i++)
		{
			int ny = s.y + vect[i].y;
			int nx = s.x + vect[i].x;
			if (ny < 0 || nx < 0 || ny >= N || nx >= M)
				continue;
			if (connect(s, { ny,nx }) && dist[ny][nx] == 0) {
				q.push({ ny, nx });
				dist[ny][nx] = dist[s.y][s.x]+1;
				cnt++;
			}
		}
	}
	return cnt;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//freopen("sample_input_2.txt", "r", stdin);
	// 0 0 5 3 6 0  / st ()2,1
	// 0 0 2 0 2 0
	// 3 3 1 3 7 0
	// 0 0 0 0 0 0
	// 0 0 0 0 0 0
	int T;
	cin >> T;
	for (int tc = 1; tc <= T; tc++)
	{
		cin >> N >> M >> R >> C >> L;
		for (int y = 0; y < N; y++)
			for (int x = 0; x < M; x++)
				cin >> map[y][x];

		memset(dist, 0, sizeof(dist));

		pos st = { R,C };
		cout << "#" << tc << " " << bfs(st, L) << "\n";
	}
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.