알고리즘
백준 16509번 장군 C++
영춘권의달인
2023. 5. 16. 16:25
https://www.acmicpc.net/problem/16509
16509번: 장군
오랜만에 휴가를 나온 호근이는 문득 동아리방에 있는 장기가 하고 싶어졌다. 하지만 장기를 오랫동안 하지 않은 탓인지 예전에는 잘 쓰던 상을 제대로 쓰는 것이 너무 힘들었다. 호근이를 위해
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;
int dRow[8] = { -1,-1, 0, 1, 1, 1, 0,-1 };
int dCol[8] = { 0, 1, 1, 1, 0,-1,-1,-1 };
int seq[8][3] = { {0,1,1},{0,7,7},{2,1,1},{2,3,3},{4,3,3},{4,5,5},{6,7,7},{6,5,5} };
struct Info {
int row;
int col;
int moveCnt;
};
vector<vector<int>> board(10, vector<int>(9, -1));
vector<vector<bool>> found(10, vector<bool>(9, false));
pair<int, int> start;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> start.first >> start.second;
int rowK, colK;
cin >> rowK >> colK;
board[rowK][colK] = 1;
queue<Info> q;
q.push({ start.first,start.second,0 });
found[start.first][start.second] = true;
int ans = -1;
while (!q.empty()) {
Info curr = q.front();
q.pop();
if (board[curr.row][curr.col] == 1) {
ans = curr.moveCnt;
break;
}
for (int i = 0; i < 8; i++) {
int nextRow = curr.row;
int nextCol = curr.col;
bool possible = true;
for (int j = 0; j < 3; j++) {
nextRow += dRow[seq[i][j]];
nextCol += dCol[seq[i][j]];
if (nextRow < 0 || nextRow >= 10 || nextCol < 0 || nextCol >= 9) {
possible = false;
break;
}
if (j!=2 && board[nextRow][nextCol]==1) {
possible = false;
break;
}
}
if (possible == false) continue;
if (found[nextRow][nextCol]) continue;
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.moveCnt + 1 });
}
}
cout << ans;
}