BFS算法题目汇总——刷完这些,搜索类题目不用担心没有思路了

HDU-2717 Catch That Cow

这是BFS最基本的入门模板题目

AC代码:

#include<iostream>
#include<queue>
using namespace std;
const int maxn = 100010;
struct Node
{
    int loc;
    int time;
};
int bfs(int start,int end);
int main()
{
    int n,k;
    while(scanf("%d %d",&n,&k)!=EOF)
        printf("%d\n",bfs(n,k));
    return 0;
}
int bfs(int start,int end)
{
    bool visit[maxn]={false};
    queue<Node> q;
    Node top;
    top.loc = start;
    top.time = 0;
    q.push(top);
    while(!q.empty())
    {
        Node temp = q.front();
        q.pop();
        if(temp.loc==end)
            return temp.time;
        for(int i=0;i<3;i++)
        {
            int next = 0;
            if(i==0)
                next = temp.loc+1;
            else if(i==1)
                next = temp.loc-1;
            else if(i==2)
                next = temp.loc*2;
            if(next<0||next>100000||visit[next])
                continue;
            visit[next]=true;
            top.time = temp.time+1;
            top.loc = next;
            q.push(top);
        }
    }
    return -1;
}

做完这道题目,我们来总结一下BFS题目最基本的框架:

while queue 不空:
    cur = queue.pop()
    for 节点 in cur的所有相邻节点:
        if 该节点有效且未访问过:
            queue.push(该节点)

HDU-1372 Knight Moves


#include<iostream>
#include<queue>
using namespace std;
const int maxn = 150;
struct Node
{
    char col;
    int row;
};
int smallestMoves(Node start,Node end);
int main()
{
    Node start,end;
    while(scanf("%c%d %c%d",&start.col,&start.row,&end.col,&end.row)!=EOF)
    {
        int minMoves = smallestMoves(start,end);
        printf("To get from %c%d to %c%d takes %d knight moves.\n",start.col,start.row,end.col,end.row,minMoves);
        getchar();
    }
    return 0;
}
int smallestMoves(Node start,Node end)
{
    int st = (start.col-'a'+1)*10+start.row;
    int ed = (end.col-'a'+1)*10+end.row;
    bool visit[maxn] = {false};
    queue<Node> q;
    int moves[maxn]={0};
    q.push(start);
    visit[st] = true;
    int dx[8]={-2,-1,-2,-1,2,1,2,1};
    int dy[8]={-1,-2,1,2,-1,-2,1,2};
    while(!q.empty())
    {
        Node top = q.front();
        q.pop();
        st = (top.col-'a'+1)*10+top.row;
        if(st==ed)
            return moves[st];
        for(int i=0;i<8;i++)
        {
            Node temp;
            temp.col = top.col+dx[i];
            temp.row = top.row+dy[i];
            int tempval = (temp.col-'a'+1)*10+temp.row;
            if(temp.col<'a'||temp.col>'h'||temp.row<1||temp.row>8||visit[tempval])
                continue;
            visit[tempval] = true;
            moves[tempval] = moves[st]+1;
            q.push(temp);
        }
    }
}
posted @ 2020-04-10 00:40  Cutey_Thyme  阅读(600)  评论(0编辑  收藏  举报