-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17141.cpp
More file actions
165 lines (149 loc) · 2.49 KB
/
17141.cpp
File metadata and controls
165 lines (149 loc) · 2.49 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// 17141. 연구소 2
// 2020.02.29
// BFS
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
int ans = 987654321;
int map[51][51];
int arr[10];
int arrVisit[10];
int n, m;
int dist[51][51];
int visit[51][51];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
vector<pair<int, int>> v;
// visit와 dist 초기화
void Init()
{
for (int i = 0; i < 51; i++)
{
fill(visit[i], visit[i] + 51, 0);
fill(dist[i], dist[i] + 51, 0);
}
}
// 바이러스 퍼뜨리는 함수
void Spread()
{
Init();
queue<pair<int, int>> q;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// 벽이면 방문표시하고 dist를 -1로 바꿈.
if (map[i][j] == 1)
{
visit[i][j] = 1;
dist[i][j] = -1;
}
}
}
// 바이러스 선택하여 방문표시하고 큐에 넣음
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j < m; j++)
{
if (arr[j] == i)
{
q.push({ v[i].first,v[i].second });
visit[v[i].first][v[i].second] = 1;
}
}
}
// BFS 실행
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
// 범위를 벗어남
if (xx < 0 || yy < 0 || xx >= n || yy >= n)
{
continue;
}
// 벽
if (map[xx][yy] == 1)
{
continue;
}
// 아직 방문하지 않았다면 방문체크 후 시간 증가
if (!visit[xx][yy])
{
dist[xx][yy] = dist[x][y] + 1;
visit[xx][yy] = 1;
q.push({ xx,yy });
}
}
}
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// 벽이 아니고 방문을 안한 칸이 있다면 바이러스 퍼뜨리기 불가능
if (map[i][j] != 1 && visit[i][j] == 0)
{
return;
}
else
{
cnt = max(cnt, dist[i][j]);
}
}
}
// 최소 시간 갱신
ans = min(ans, cnt);
}
// 2가 있는 들어가있는 것들 중 m개 선택하는 함수
void go(int cnt, int idx)
{
if (cnt == m)
{
// 모두 선택했다면 바이러스를 퍼뜨림
Spread();
return;
}
for (int i = idx; i < v.size(); i++)
{
if (!arrVisit[i])
{
arrVisit[i] = 1;
arr[cnt] = i;
go(cnt + 1, i);
arrVisit[i] = 0;
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> map[i][j];
if (map[i][j] == 2)
{
v.push_back({ i,j });
}
}
}
go(0, 0);
if (ans == 987654321)
{
cout << -1 << endl;
}
else
{
cout << ans << endl;
}
return 0;
}