[๋ฐฑ์ค(BOJ)] ๋ฐฑ์กฐ์ ํธ์(3197) C++
๋ฌธ์ : BOJ_3197๋ฒ ๋ฐฑ์กฐ์ ํธ์
๋ฌธ์ ์ค๋ช
์ด๋ถํ์, bfs
๋ฌผ ๊ณต๊ฐ๊ณผ ๋นํ ๊ณต๊ฐ์ด ์๋ ์ง๋๊ฐ ์ฃผ์ด์ง๊ณ , L
์ ๋ ๋ฐฑ์กฐ์ ์์น๊ฐ ์ฃผ์ด์ง๋๋ค.
๋ฌผ ๊ณต๊ฐ๊ณผ ๊ฐ๋ก, ์ธ๋ก๋ก ์ ํ ๋นํ ๋ถ๋ถ์ด ํ๋ฃจ์ ํ ๋ฒ์ฉ ๋
น๋๋ฐ, ์ด๋ ๋ ๋ฐฑ์กฐ๊ฐ ๋ง๋ ์ ์๋ ์ต์์ ๋ ์ ๊ณ์ฐํ๋ ๋ฌธ์ ์
๋๋ค.
์ด ๋ฌธ์ ๋ ํ๋ฃจ์ ํ ๋ฒ์ฉ ๋
น๋ ๋นํ ๋ถ๋ถ๋ ๊ณ ๋ คํด์ผ ํ๊ณ , ๋ ๋นํ์ด ๋
น์์ ๋ ๋ง๋ ์ ์๋ ์ต์์ ๋ ๋ ๊ตฌํด์ผ ํ๊ธฐ ๋๋ฌธ์ bfs์ ์ด๋ถ ํ์ ๋ ๊ฐ์ง๊ฐ ์ฐ์ด๋ ๋ฌธ์ ์
๋๋ค.
Solution
์ฒ์์ bfs๋ฅผ ์ด์ฉํ์ฌ ๋นํ์ด ๋ชจ๋ ๋
น๋ ์ต๋ ๋ ์ ์ด๋ถ ํ์์ max ๊ฐ์ผ๋ก ์ง์ ํด ์ฃผ๊ณ ์ด๋ถ ํ์์ ์คํํฉ๋๋ค.
์ต์๊ฐ๊ณผ ์ต๋๊ฐ์ ์ค๊ฐ๊ฐ์ผ๋ก bfs๋ฅผ ๋๋ฆฌ๋ฉฐ ์ค๊ฐ๊ฐ์ ๋ ์ด ๋๊ธฐ ์ ์ ๋ฐฑ์กฐ๋ฅผ ๋ง๋๋ค๋ฉด ์ต์๊ฐ์ ์ฌ๋ ค์ฃผ๊ณ , ๋ง๋์ง ๋ชปํ๋ค๋ฉด ์ต๋๊ฐ์ ๋ฎ์ถฐ์ฃผ๋ฉฐ ์ด๋ถ ํ์์ ์งํํ์ต๋๋ค.
์ด๋ ๊ฒ ๊ตฌํ ์ต์ ํด๊ฐ ๋ ๋ฐฑ์กฐ๊ฐ ๋ง๋ ์ ์๋ ์ต์์ ๋ ์
๋๋ค.
Description
- ๋ ๋ฐฑ์กฐ์ ์์น๋ฅผ
vector<pair<int, int>> v
๋ก ์ ์ธํ์ฌ ํํํ์ต๋๋ค. - ํน์ ์์น๋ฅผ ๋ฐฉ๋ฌธํ ํ์๋ฅผ
vis
๋ฐฐ์ด๋ก ์ฒดํฌํ๊ณ , ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ํ์ธํ๊ธฐ ์ํด -1๋ก ์ด๊ธฐํํ๊ณ ์์ํ์ต๋๋ค. vis
์ -1 ์ด๊ธฐํ๋ memset์ ์ด์ฉํ์ต๋๋ค.
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;
char map[1501][1501];
int vis[1501][1501];
int now_vis[1501][1501];
vector<pair<int, int>> v;
void bfs(void);
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
int r, c;
int le = 0;
int ri = 1500 * 2+1;
int res_max = 0;
queue<pair<int, int>> q;
int main(void) {
memset(vis, -1, sizeof(vis));
scanf("%d%d", &r, &c);
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
scanf(" %c", &map[i][j]);
if (map[i][j] == '.') {
vis[i][j] = 0;
q.push({ i,j });
now_vis[i][j] = 1;
}
else if (map[i][j] == 'L') {
v.push_back({ i,j });
vis[i][j] = 0;
q.push({ i,j });
now_vis[i][j] = 1;
}
}
}
bfs();
ri = res_max;
while (le <= ri) {
memset(now_vis, 0, sizeof(now_vis));
now_vis[v[0].first][v[0].second] = 1;
int swc = 0;
int mi = (le + ri) / 2;
queue<pair<int, int>> res;
res.push({ v[0].first,v[0].second });
while (!res.empty()) {
int x = res.front().first;
int y = res.front().second;
res.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<1 || ny<1 || nx>r || ny>c) continue;
if (nx == v[1].first && ny == v[1].second) {
swc++;
break;
}
if (vis[nx][ny] > mi) continue;
if (now_vis[nx][ny]) continue;
now_vis[nx][ny] = 1;
res.push({ nx,ny });
}
}
if (swc) ri = mi - 1;
else le = mi + 1;
}
printf("%d\n", le);
}
void bfs(void) {
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<1 || ny<1 || nx>r || ny>c) continue;
if (map[nx][ny] == 'L') continue;
if (now_vis[nx][ny]) continue;
if (vis[nx][ny] == -1) {
vis[nx][ny] = vis[x][y] + 1;
res_max = max(res_max, vis[nx][ny]);
now_vis[nx][ny] = 1;
q.push({ nx,ny });
}
}
}
}
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] ์ธํ์ ์ํ(2098) (0) | 2022.03.11 |
---|---|
[BOJ] ์ค๋์ฟ (2580) (0) | 2022.03.10 |
[BOJ] ํ์ ํ๊ธฐ์(1918) (0) | 2022.03.10 |
[BOJ] ํ์ด์ ๋ฐํด(2840) (0) | 2022.03.10 |
[BOJ] ํ์ ํ๋ ํ(1021) (0) | 2022.03.10 |