COJ 1511:残缺的棋盘

5 篇文章 0 订阅

温习bfs


题目链接

点击打开链接


#include <stdio.h>
#include <queue>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

//int n;
int Map[8][8];
int ex,ey,sx,sy,r,c;

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

struct Node
{
    int x,y,step;
};


 int check(int x,int y)
{
  if(x>=0&&x<8&&y>=0&&y<8&&Map[x][y]==0)
    return 1;
  else
    return 0;
}

int BFS(int x, int y)
{
//    if (sx == ex && sy == ey)
//    {
//        printf("0\n");
//        return;
//    }
    Node temp;
    Node next;
    queue<Node> Queue;
    temp.x = x;
    temp.y = y;
    temp.step=0;
    Map[x][y]=1;
    Queue.push(temp);
    while(!Queue.empty())
    {
        temp=Queue.front();
        Queue.pop();
        if(temp.x==ex&&temp.y==ey)
        {
            //printf("Case 1: 7%d\n",temp.step);
            return temp.step;
        }

        else

            for (int i=0; i<8;i++)
        {
            next.x=temp.x+dir[i][0];
            next.y=temp.y+dir[i][1];

            if(check(next.x,next.y)==1)
            {
                if(next.x==r&&next.y==c)
                        continue;
                next.step=temp.step+1;
                Map[next.x][next.y]=1;
                Queue.push(next);
            }
        }
    }
    return -1;
}

int main()
{
    int t=0;
    int ans;
//int ex,ey,sx,sy;
   // scanf("%d",&t);
    while(~scanf("%d %d %d %d %d %d",&sx,&sy,&ex,&ey,&r,&c))
    {
            t++;
        memset(Map,0,sizeof(Map));
        //scanf("%d",&n);
        //scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
        sx--;sy--;ex--;ey--;r--;c--;
        ans=BFS(sx,sy);
        printf("Case %d: %d\n",t,ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值