数据结构总结之bfs

1.模板题uva439的模板:
其实就是用queue,结构体node,vis数组,步数(路径)都可以放在结构体里面

#include<iostream>
#include<cstring>
#include<string>
#include<queue>
#include<cmath>
using namespace std;
const int MAXN = 8 + 2;
struct Node
{
    int x, y, d;
    Node() {}
    Node(int x,int y,int d=0):x(x),y(y),d(d) {}
};
int vis[MAXN][MAXN];
Node start, dest;

bool isvalid(int x, int y)
{
    return x > 0 && x < 9 && y > 0 && y < 9;
}
int dir[8][2]= {-2,-1,-2,1,-1,-2,-1,2,1,-2,2,-1,2,1,1,2};
void bfs()
{
    queue<Node> q;
    q.push(start);
    while (!q.empty())
    {
        Node horse = q.front();
        q.pop();
        for(int i=0; i<8; i++)
        {
            int x = horse.x + dir[i][0];
            int y = horse.y + dir[i][1];
            if ( isvalid(x, y) && !vis[x][y])
            {
                if (dest.x == x && dest.y == y)
                {
                    dest.d = horse.d + 1;
                    return;
                }
                vis[x][y] = 1;
                q.push(Node(x, y, horse.d +1));
            }
        }
    }
}
int main()
{
    string s1, s2;
    while (cin >> s1 >> s2)
    {
        memset(vis, 0, sizeof(vis));
        start.x = s1[0] - 'a' + 1;
        start.y = s1[1] - '0';
        start.d = 0;//横纵都从1开始
        dest.x = s2[0] - 'a' + 1;
        dest.y = s2[1] - '0';
        dest.d = 0;
        vis[start.x][start.y] = 1;
        bfs();
        cout << "To get from "<<s1<<" to "<<s2<<" takes "<<dest.d<<" knight moves.\n";
    }
    return 0;
}

2.bfs适用于“以层计数”的递归结构,如:uva417

#include <iostream>
#include <map>
#include <stdio.h>
#include <string>
#include <queue>
using namespace std;
map<string,int> m;
queue<string> q;
int cnt;
char ch[26];
void bfs()
{
    q.push("");
    while(!q.empty())
    {
        string v=q.front();
        q.pop();
        int t;
        if(v.length()) t=*(v.end()-1)-'a'+1;
        else t=0;
        for(int i=t;i<26;i++)
        {
            string u=v+ch[i];
            if(u.length()==6) return ;
            q.push(u);
            m[u]=++cnt;
        }
    }
}
int main()
{
    ch[0]='a';
    for(int i=1;i<26;i++)
        ch[i]=ch[i-1]+1;
    bfs();
    char r[6];
    while(~scanf("%s",r))
    {
        if(m.count(r))
        printf("%d\n",m[r]);
        else
            printf("0\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值