[백준 7562번] 나이트의 이동

2021. 11. 16. 17:02·알고리즘 문제풀이/백준
반응형

문제 링크:https://www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

 

<문제 풀이> BFS

기본적인 BFS 최단거리 문제랑 똑같은데 방향만 8방향으로 설정해주면 됩니다.

int dx[8] = {-2, -1, 1, 2, -2, -1, 1, 2};
int dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};

 

<C++ 소스 코드>

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#include <utility>
#include <climits>
using namespace std;
 
#define X first
#define Y second
 
int dx[8] = {-2, -1, 1, 2, -2, -1, 1, 2};
int dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int visited[300][300];
 
int bfs(int n, int cx, int cy, int wx, int wy) {
    queue<pair<int, int> > Q;
    Q.push({ cx, cy });
    visited[cx][cy] = 0;
    if (cx == wx && cy == wy) return visited[wx][wy];
    while (!Q.empty()) {
        auto cur = Q.front(); Q.pop();
        cx = cur.X;
        cy = cur.Y;
        for (int dir = 0; dir < 8; dir++) {
            int nx = cx + dx[dir];
            int ny = cy + dy[dir];
            if (nx < 0 || ny < 0 || nx >= n || ny >= n) continue;
            if (visited[nx][ny] != -1) continue;
            Q.push({ nx, ny });
            visited[nx][ny] = visited[cx][cy] + 1;
            if (nx == wx && ny == wy) return visited[wx][wy];
        }
    }
}
 
int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int test_case; cin >> test_case;
    while (test_case--) {
        int n; cin >> n;
        int cx, cy; cin >> cx >> cy;
        int wx, wy; cin >> wx >> wy;
        fill(&visited[0][0], &visited[299][300], -1);
        cout << bfs(n, cx, cy, wx, wy)<<'\n';
    }
  
    return 0;
}
 
Colored by Color Scripter
cs

 

 

반응형
저작자표시 (새창열림)

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 2146번] 다리 만들기  (0) 2021.11.19
[백준 5427번] 불  (0) 2021.11.17
[백준 10026번] 적록색약  (0) 2021.11.05
[백준 4179번] 불!  (0) 2021.11.04
[백준 7576번] 토마토  (0) 2021.11.03
'알고리즘 문제풀이/백준' 카테고리의 다른 글
  • [백준 2146번] 다리 만들기
  • [백준 5427번] 불
  • [백준 10026번] 적록색약
  • [백준 4179번] 불!
슥지니
슥지니
개발 블로그
  • 슥지니
    슥지니의 코딩노트
    슥지니
  • 전체
    오늘
    어제
    • 분류 전체보기 (198)
      • 알고리즘 문제풀이 (158)
        • 백준 (158)
      • 알고리즘 (6)
      • Node.js (2)
        • MongoDB (1)
        • 기타 (1)
      • spring (0)
      • 가상화폐 (1)
        • 바이낸스(Binance) (1)
      • C++ 테트리스 게임 (0)
      • C++ (10)
      • 안드로이드 프로그래밍 (21)
        • 코틀린 (21)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    BFS
    우선순위 큐
    콘솔
    그리디
    백준
    C++
    코틀린을 활용한 안드로이드 프로그래밍
    Kotlin
    dfs
    자료구조
    그래프
    백트랙킹
    시뮬레이션
    dp
    다이나믹 프로그래밍
    코틀린
    콘솔 테트리스 게임
    구현
    알고리즘
    C
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
슥지니
[백준 7562번] 나이트의 이동
상단으로

티스토리툴바