알고리즘
백준 2194번 유닛 이동시키기 C++
영춘권의달인
2023. 2. 9. 14:56
https://www.acmicpc.net/problem/2194
2194번: 유닛 이동시키기
첫째 줄에 다섯 개의 정수 N, M(1 ≤ N, M ≤ 500), A, B(1 ≤ A, B ≤ 10), K(0 ≤ K ≤ 100,000)가 주어진다. 다음 K개의 줄에는 장애물이 설치된 위치(행 번호, 열 번호)가 주어진다. 그 다음 줄에는 시작점의
www.acmicpc.net
일반적인 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;
struct Info {
int row;
int col;
int moveCnt;
};
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
int n, m, a, b, k;
vector<vector<int>> board;
vector<vector<bool>> found;
pair<int, int> targetPos;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m >> a >> b >> k;
board = vector<vector<int>>(n + 1, vector<int>(m + 1, 0));
found = vector<vector<bool>>(n + 1, vector<bool>(m + 1, false));
for (int i = 0; i < k; i++) {
int r, c;
cin >> r >> c;
board[r][c] = -1;
}
int sr, sc;
int er, ec;
cin >> sr >> sc >> er >> ec;
queue<Info> q;
q.push({ sr,sc,0 });
found[sr][sc] = true;
targetPos = { er,ec };
int ans = -1;
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (curr.row == targetPos.first && curr.col == targetPos.second) {
ans = curr.moveCnt;
break;
}
for (int i = 0; i < 4; i++) {
bool canGo = true;
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) continue;
int nnextRow = nextRow + a - 1;
int nnextCol = nextCol + b - 1;
if (nnextRow <= 0 || nnextRow > n) continue;
if (nnextCol <= 0 || nnextCol > m) continue;
for (int j = nextRow; j <= nnextRow; j++) {
for (int k = nextCol; k <= nnextCol; k++) {
if (board[j][k] == -1) canGo = false;
}
}
if (canGo == false) continue;
q.push({ nextRow,nextCol,curr.moveCnt + 1 });
found[nextRow][nextCol] = true;
}
}
cout << ans;
}