数据结构总结之bfs

来源:互联网 发布:hadoop 处理数据 编辑:程序博客网 时间:2024/05/16 14:44

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;}