Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Unreal Engine 5
- 재귀
- 그래프
- 우선순위 큐
- BFS
- 알고리즘
- 스택
- 구현
- c++
- 브루트포스
- 유니온 파인드
- 다이나믹 프로그래밍
- 그리디 알고리즘
- 정렬
- DFS
- 자료구조
- 누적 합
- 문자열
- 투 포인터
- 시뮬레이션
- Team Fortress 2
- ue5
- XR Interaction Toolkit
- 백트래킹
- VR
- 백준
- 트리
- 다익스트라
- 수학
- 유니티
Archives
- Today
- Total
1일1알
백준 1261번 알고스팟 C++ 본문
앞에 벽이 있거나 없는 경우가 있다. 있으면 벽을 부수고 없으면 그냥 간다. 구해야 하는 답은 벽을 최소 몇 개 부수어야 하는지 이기 때문에 bfs로 탐색할 때 벽을 부순 횟수가 가장 적은 경우가 가장 앞에 있어야 한다. 그렇기 때문에 우선순위 큐를 사용해서 bfs를 통해 풀었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, m;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
struct Vertex {
int row;
int col;
int cnt;
bool operator<(const Vertex& other) const {
return cnt < other.cnt;
}
bool operator>(const Vertex& other) const {
return cnt > other.cnt;
}
};
vector<vector<int>> board;
vector<vector<bool>> found;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> m >> n;
board = vector<vector<int>>(n, vector<int>(m));
found = vector<vector<bool>>(n, vector<bool>(m, false));
for (int i = 0; i < n; i++) {
string str;
cin >> str;
for (int j = 0; j < m; j++) {
board[i][j] = str[j] - '0';
}
}
priority_queue<Vertex, vector<Vertex>, greater<Vertex>> pq;
pq.push({ 0,0,0 });
found[0][0] = true;
int ans = 0;
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
if (curr.row == n - 1 && curr.col == m - 1) {
ans = curr.cnt;
break;
}
for (int i = 0; i < 4; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow < 0 || nextRow >= n) continue;
if (nextCol < 0 || nextCol >= m) continue;
if (found[nextRow][nextCol]) continue;
if (board[nextRow][nextCol] == 1) {
board[nextRow][nextCol] = 0;
found[nextRow][nextCol] = true;
pq.push({ nextRow,nextCol,curr.cnt + 1 });
}
else {
found[nextRow][nextCol] = true;
pq.push({ nextRow,nextCol,curr.cnt });
}
}
}
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 14402번 가장 긴 증가하는 부분 수열 4 C++ (0) | 2022.08.13 |
---|---|
백준 1339번 단어 수학 C++ (0) | 2022.08.12 |
백준 3055번 탈출 C++ (0) | 2022.08.10 |
백준 1922번 네트워크 연결 C++ (0) | 2022.08.09 |
백준 1707번 이분 그래프 C++ (0) | 2022.08.08 |