Notice
Recent Posts
Recent Comments
Link
Tags
- ์์ฝ๋
- ํ๋ฆฌ์จ๋ณด๋ฉ
- nestjs
- js
- ๋ฐฑ์๋ ํ๋ฆฌ์จ๋ณด๋ฉ
- ๋ค์ต์คํธ๋ผ
- ์ด๋ถํ์
- BFS
- ์นด์นด์ค ์ฝํ
- go
- ์๊ณ ๋ฆฌ์ฆ
- ๋นํธ๋งต
- ๊ฐ์ฅ๊ฐ๊น์ด๊ณตํต์กฐ์
- ์นด์นด์ค2021
- ์ํฐ๋
- C++
- ๋ฐฑ์ค
- golang
- ๋์ ํ๋ก๊ทธ๋๋ฐ
- DP
- ํ๋ก๊ทธ๋๋จธ์ค
- ์ฌ๊ท
- ํธ๋ฆฌ
- Python
- LCs
- DFS
- Union-Find
- ๋นํธ๋ง์คํน
- ์ฌ๋ผ์ด๋ฉ ์๋์ฐ
- ์น๋ฆฐ์ด
Archives
- Today
- Total
Hello Ocean! ๐ผ
[๋ฐฑ์ค/C++] 2206. ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ ๋ณธ๋ฌธ
๋ฐ์ํ
๋ฌธ์
ํ์ด
์์์๊ฐ : 2์๊ฐ
BFS๋ฅผ ์ด์ฉํด์ ํ์๋ค.
๊ตฌ์กฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ํ์ ๋ฃ์๋ค.
๋ฐฉ๋ฌธ์ฌ๋ถ๋ฅผ ๊ฒ์ฌํ ๋, ํด๋น ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ธฐ ์ ์ ๋ฒฝ์ ๋ถ์ ์ ์ด ์๋์ง ์๋์ง๋ฅผ ๊ตฌ๋ณํด์ ๊ฒ์ฌํ๋ค.
์ฝ๋
/* ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ */
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int N, M;
bool map[1001][1001];
bool visited[2][1001][1001] = { 0, };
int answer = 987654321;
int dn[4] = { -1,1,0,0 };
int dm[4] = { 0,0,-1,1 }; // ์ ํ ์ข ์ฐ
struct Node {
int n;
int m;
int dist;
bool crashWall;
};
void BFS() {
queue<Node> q;
q.push({1,1,1,0}); // idx : 1 ~ N, 1 ~ M
visited[1][1][1] = 1;
visited[0][1][1] = 1;
while (!q.empty()) {
Node temp = q.front();
int n = temp.n;
int m = temp.m;
int dist = temp.dist;
bool crashWall = temp.crashWall;
q.pop();
if (n == N && m == M) {
answer = dist;
return;
}
for (int i = 0;i < 4;i++) {
int new_n = n + dn[i];
int new_m = m + dm[i];
if (new_n > 0 && new_n <= N && new_m > 0 && new_m <= M) { //map ๋ฒ์ ์์ธ์ง ํ์ธ
if (map[new_n][new_m]) { //๋ฒฝ
if (!crashWall && !visited[!crashWall][new_n][new_m]) { //๋ฒฝ์ ๋ถ์ ์ ์ด ์๊ณ , ํด๋น ์์น๋ฅผ ๋ฒฝ์ ๋ถ์ ์ฑ๋ก ๋ฐฉ๋ฌธํ ์ ์ด ์์ผ๋ฉด
q.push({ new_n,new_m,dist + 1,!crashWall });
visited[!crashWall][new_n][new_m] = 1;
}
}
else { //๋ฒฝ์ด ์๋
if (!visited[crashWall][new_n][new_m]) {
q.push({ new_n,new_m,dist + 1,crashWall });
visited[crashWall][new_n][new_m] = 1;
}
}
}
}
}
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
string s;
for (int i = 1;i <= N;i++) {
cin >> s;
for (int j = 1;j <= M;j++) {
map[i][j] = s[j-1] - '0';
}
}
BFS();
if (answer == 987654321)
answer = -1;
cout << answer << endl;
return 0;
}
๊ฒฐ๊ณผ
๋ฌด์ํ ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ์ ๊ธฐ๋ก...
-> BFS์์ q์ pushํ ๋, visited๋ฅผ ์ฒดํฌํด์ค์ผ ํ๋๋ฐ, q์์ ๊บผ๋ด๊ณ ๋์ ์ฒดํฌํ๋๋ ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ๊ฐ ๋ฌ๋ค..
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค/C++] 2589. ๋ณด๋ฌผ์ฌ (0) | 2021.05.19 |
---|---|
[๋ฐฑ์ค/C++] 1707. ์ด๋ถ๊ทธ๋ํ (0) | 2021.05.12 |
[๋ฐฑ์ค/C++] 16236.์๊ธฐ์์ด (0) | 2021.05.04 |
[๋ฐฑ์ค/C++] 1987. ์ํ๋ฒณ (0) | 2021.05.04 |
[๋ฐฑ์ค/C++] 1238. ํํฐ (0) | 2021.04.28 |