CSU-1511 残缺的棋盘 解题报告

来源:互联网 发布:淘宝5.9下载 编辑:程序博客网 时间:2024/05/01 12:18

  这是第一道我自己独立解决的BFS题,也让我充分的掌握了BFS的代码模板,虽然是一道水题,但对我还是蛮有意义的。

  本题的思路也是非常的简单,直接利用BFS通过广搜找到最小路径就OK了,中间注意标记已走过的路(和DFS不同,不用还原)还有那个被锁定的格子。

代码如下:

#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>using namespace std;int r1,c1,r2,c2,r3,c3,head,flag,tail,tx,ty;int vis[9][9];int dx[8]={-1,-1,-1,0,0,1,1,1};int dy[8]={-1,0,1,-1,1,-1,0,1};int cnt=0;struct node{    int x,y,f,s;}a[200];void bfs(){   head=1;   tail=1;   flag=0;   a[tail].x=r1;   a[tail].y=c1;   a[tail].s=0;   tail++;   while(head<tail)   {       for(int k=0;k<8;k++)       {           tx=a[head].x+dx[k];           ty=a[head].y+dy[k];           if(tx==r3&&ty==c3||tx<1||ty<1||tx>8||ty>8)            continue;          if(vis[tx][ty]==0)            {                vis[tx][ty]=1;                a[tail].x=tx;                a[tail].y=ty;                a[tail].s=a[head].s+1;                tail++;            }           if(tx==r2&&ty==c2)            {               flag=1;               break;            }            //cout<<tail<<endl;       }        if(flag)            break;     head++;   }   cout<<"Case "<<++cnt<<": "<<a[tail-1].s<<endl;}int main(){    int T=10010;    while(scanf ("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3)==6)    {        memset(vis,0,sizeof(vis));        vis[r1][c1]=1;        bfs();    }    return 0;}
这题当然也可以用队列去做,不过我现在更喜欢这种做法。

 

0 0
原创粉丝点击