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
- 브루트포스
- c++
- 우선순위 큐
- 누적 합
- 투 포인터
- Team Fortress 2
- 재귀
- 유니티
- 구현
- VR
- 그리디 알고리즘
- 백준
- 자료구조
- 알고리즘
- 그래프
- 문자열
- 스택
- 백트래킹
- 정렬
- BFS
- ue5
- 시뮬레이션
- Unreal Engine 5
- 다이나믹 프로그래밍
- DFS
- 다익스트라
- 유니온 파인드
- 트리
- XR Interaction Toolkit
- 수학
Archives
- Today
- Total
1일1알
백준 18404번 현명한 나이트 C++ 본문
https://www.acmicpc.net/problem/18404
18404번: 현명한 나이트
첫째 줄에 N과 M이 공백을 기준으로 구분되어 자연수로 주어진다. (1 ≤ N ≤ 500, 1 ≤ M ≤ 1,000) 둘째 줄에 나이트의 위치 (X, Y)를 의미하는 X와 Y가 공백을 기준으로 구분되어 자연수로 주어진다. (
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[8] = { -2,-1, 1, 2, 2, 1,-1,-2 };
int dCol[8] = { 1, 2, 2, 1,-1,-2,-2,-1 };
int n, m;
pair<int, int> startPos;
vector<pair<int, int>> targetPoses;
vector<vector<int>> moveCnts;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
targetPoses = vector<pair<int, int>>(m);
moveCnts = vector<vector<int>>(n + 1, vector<int>(n + 1, -1));
cin >> startPos.first >> startPos.second;
for (int i = 0; i < m; i++) {
cin >> targetPoses[i].first >> targetPoses[i].second;
}
queue<Info> q;
moveCnts[startPos.first][startPos.second] = 0;
q.push({ startPos.first,startPos.second,0 });
while (!q.empty()) {
auto curr = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow <= 0 || nextRow > n) continue;
if (nextCol <= 0 || nextCol > n) continue;
if (moveCnts[nextRow][nextCol] >= 0) continue;
moveCnts[nextRow][nextCol] = curr.moveCnt + 1;
q.push({ nextRow,nextCol,curr.moveCnt + 1 });
}
}
for (int i = 0; i < m; i++) {
cout << moveCnts[targetPoses[i].first][targetPoses[i].second] << " ";
}
}
'알고리즘' 카테고리의 다른 글
백준 3182번 한동이는 공부가 하기 싫어! C++ (0) | 2023.06.07 |
---|---|
백준 19637번 IF문 좀 대신 써줘 C++ (1) | 2023.06.06 |
백준 1986번 체스 C++ (0) | 2023.06.01 |
백준 15664번 N과 M(10) C++ (0) | 2023.05.30 |
백준 20365번 블로그2 C++ (0) | 2023.05.29 |