Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Tags
more
Archives
Today
Total
관리 메뉴

devchang

백준 7562(나이트의 이동) 풀이 본문

알고리즘

백준 7562(나이트의 이동) 풀이

devchang 2024. 9. 24. 14:37

문제

입력

출력

 

문제풀이

#include <iostream>
#include <queue>

using namespace std;

int main()
{
  cin.tie(NULL);
  ios::sync_with_stdio(false);
  int t, n;
  int inx, iny;
  queue<pair<int, pair<int, int>>> q;
  int x[8] = {-2, -1, 2, 1, -2, -1, 2, 1};
  int y[8] = {-1, -2, 1, 2, 1, 2, -1, -2};
  int ocnt = 0;
  bool finish = false;

  cin >> t;

  for (int i = 0; i < t; i++)
  {
    ocnt = 0;
    finish = false;
    bool vis[300][300] = {
        false,
    };
    int a[300][300] = {
        0,
    };
    cin >> n;
    cin >> inx >> iny;
    a[inx][iny] = 1;
    vis[inx][iny] = true;
    q.push({0, {inx, iny}});
    cin >> inx >> iny;
    a[inx][iny] = 1;

    while (!q.empty())
    {
      pair<int, pair<int, int>> tmp = q.front();
      q.pop();

      for (int i = 0; i < 8; i++)
      {
        int tmpx = tmp.second.first + x[i];
        int tmpy = tmp.second.second + y[i];
        int tmpcnt = tmp.first;


        if (tmpx < 0 || tmpy < 0 || tmpx > n - 1 || tmpy > n - 1)
        {
          continue;
        }

        if (vis[tmpx][tmpy])
        {
          continue;
        }

        if (a[tmpx][tmpy] == 1)
        {
          ocnt = tmpcnt + 1;
          finish = true;
          break;
        }

        q.push({tmpcnt + 1, {tmpx, tmpy}});
        vis[tmpx][tmpy] = true;
      }
      if(finish){
        break;
      }
    }

    cout << ocnt << "\n";

    while (!q.empty()) q.pop();
  }
}

 

이 문제는 bfs로 해결할 수 있다.

 

기존 bfs에서는 상하좌우를 방문했다면 

이 문제에서는 나이트처럼 ㄴ모양으로 방문을 하도록 하면 된다.

 

그 방법으로는 원래 상하좌우를 방문하기 위해

int x[4] = {-1, 0, 1, 0};
int y[4] = {0, -1, 0, 1};

를 사용했다면

int x[8] = {-2, -1, 2, 1, -2, -1, 2, 1};
int y[8] = {-1, -2, 1, 2, 1, 2, -1, -2};

로 바꿔서 ㄴ모양으로 방문하도록 하면 해결된다.

'알고리즘' 카테고리의 다른 글

백준 10026(적록색약) 풀이  (0) 2024.09.24
백준 4179(불!) 풀이  (0) 2024.09.24
백준 7576(토마토) 풀이  (0) 2024.09.24
백준 1920번(수 찾기) 풀이  (1) 2024.04.20
알고리즘  (0) 2024.04.20