白駿7562 Knight Moves


質問アドレス:https://www.acmicpc.net/problem/7562
使用するアルゴリズム:幅優先ナビゲーション(bfs)
->使用理由:目的の目的地に到達する最小回数です.したがって、最初に移動できる場合は、数をすべて移動できます.
次に、移動可能であれば、数を回して、目的地に到着すれば、目的地に到着する最小移動回数です.
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
struct dir{
    int x,y;
};
struct qu{
    int x,y,val;
};

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

int len,s_x,s_y,end_x,end_y;
int ch[301][301];
vector<int>res;
int cnt;
queue<qu>q;
void bfs()
{
   
    int x, y;
    while(!q.empty()){
        x=q.front().x;
        y=q.front().y;
        cnt=q.front().val;
        q.pop();
        int nx,ny;
        if(x==end_x&&y==end_y){
            res.push_back(cnt);
            break;
        }
        for(int i=0;i<8;i++){
            nx=x+dx[i].x;
            ny=y+dx[i].y;
            if(nx>=0&&ny>=0&&nx<len&&ny<len){
                if(ch[nx][ny]==0){
                    ch[nx][ny]=1;
                    q.push({nx,ny,cnt+1});
                }
            }
           
        }
    }

    
    
    
}

int main(){
    
    cin.tie(0);
    cout.tie(0);
    std::ios::sync_with_stdio(false);
    
    cin>>test;
  
    //반복 횟수 입력
    while(test--){
        //체스판 길이 입력
        cin>>len;
        //시작점의 행과 열값 입력
        cin>>s_x>>s_y;
        //도착점의 행과 열값 입력
        cin>>end_x>>end_y;
        //bfs를 사용하기 위해 선언한 큐에 시작점과 이동횟수값을 넣음
        q.push({s_x,s_y,0});
        bfs();
        //도착수의 중복방지를 위해 선언한 배열
        memset(ch, 0, sizeof(ch));
        while(!q.empty()){
            q.pop();
        }
        
    }
    
    for(int i=0;i<res.size();i++){
        cout<<res[i]<<"\n";
    }
    
    
    
    return 0;
}
最初にqueueをグローバル変数として宣言した後、繰り返すたびにキューが空になっていないのは間違っています.
複数回実行する場合は、変数の初期化にもっと注意する必要がある場合があります.
*より良い回答があれば、一緒に共有してください!気になるところがあれば気軽にコメントしてください^^