一本通 1.4 例3 Knight Moves(广搜)

题目链接:https://loj.ac/problem/10028

       好久没写搜索题了,找一道练练手,这道题描述可能稍微有点问题,说是n*n的地图,然后发现样例中地图大小包括了0 0点和n n点,其他就没什么了,裸的广搜,主要就是构建dir数组。


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 305
using namespace std;
struct Node{
  int x,y,step;
}Now,Next,S,E;
int vis[maxn][maxn];
int dir[8][2] = {1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};
int T,n;

bool Check(int x,int y){
  if(x >= 0 && y >= 0 && x <= n && y <= n && vis[x][y] == 0)return true;
  return false;
}

int bfs(){
  memset(vis,0,sizeof(vis));
  S.step = 0;
  queue<Node> q;
  q.push(S);
  while(!q.empty()){
    Now = q.front();
    q.pop();
    if(Now.x == E.x && Now.y == E.y){
      return Now.step;
    }
    for(int i=0;i<8;i++){
      Next.x = Now.x + dir[i][0];
      Next.y = Now.y + dir[i][1];
      if(Check(Next.x,Next.y)){
        vis[Next.x][Next.y] = 1;
        Next.step = Now.step + 1;
        q.push(Next);
      }
    }
  }
  return 0;
}

int main()
{
  scanf("%d",&T);
  while(T--){
    scanf("%d",&n);
    scanf("%d%d%d%d",&S.x,&S.y,&E.x,&E.y);
    if(S.x == E.x && S.y == E.y){
      printf("0\n");
      continue;
    }
    int ans = bfs();
    printf("%d\n",ans);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/charles_zaqdt/article/details/81141242