zoukankan      html  css  js  c++  java
  • dfs和bfs专题

                                    A.棋盘问题
    在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

    Input

    输入含有多组测试数据。 
    每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n 
    当为-1 -1时表示输入结束。 
    随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。 

    Output

    对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

    Sample Input

    2 1
    #.
    .#
    4 4
    ...#
    ..#.
    .#..
    #...
    -1 -1
    

    Sample Output

    2
    1
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    char map[20][20];
    int vis[20];
    int sum,cnt,n,k;
    void dfs(int s)
    {
        if(cnt==k)
        {
            sum++;
            return ;
        }
        else
        {
            if(s>=n)//出界 
            {
                return ;
            }
            for(int i=0;i<n;i++)
            {
                if(!vis[i]&&map[s][i]=='#')
                {
                    vis[i]=1;
                    cnt++;
                    dfs(s+1);
                    cnt--;//回溯一次就要建一个棋子。
                    vis[i]=0; //和上面那一步理解一样 
                }
            }
            dfs(s+1);//继续下下一种方案,直到全部扫描完     
        }
    }
    int main()
    {
        while(cin>>n>>k)
        {
            if(n==-1&&k==-1) break;  
            memset(map,0,sizeof(map));
            memset(vis,0,sizeof(vis));
            for(int i=0;i<n;i++)
                for(int j=0;j<n;j++)
                {
                    cin>>map[i][j];
                }
            cnt=0;sum=0;
            dfs(0);
            cout<<sum<<endl;
        }
        return 0;
     } 
    View Code
    在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
    你的任务是,对于给定的N,求出有多少种合法的放置方法。

    Input
    共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
    Output
    共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
    Sample Input
    1 8 5    0
    Sample Output
    1  92 10
    这到题要打表。
    #include <cstdio>
    #include <cmath>
    int qizi[20];//qizi【i】=j表示 第i行第j列下有棋 
    int biao[11];//结果存到表中,不存会超时 
    int n;
    int qingkuang;
    bool judge(int hang)
    {
        for(int i=1;i<hang;i++)//扫之前下过棋每一行是否有与此次所下棋的位置同列的 或同对角线的 
        {
            if(qizi[i]==qizi[hang]||abs(hang-i)==abs(qizi[hang]-qizi[i]))//对角线的话斜率的绝对值=1 
            return false; 
        }
        return true;
    }
     
    void dfs(int hang)
    {
        if(hang==n+1)//比如n=2,然后该第二行下棋了,第二行如果能成功选择的话,那么那么新的行数3就等于n+1=3了 ,实在不懂举个例子看看 
        qingkuang++;
        else
        {
            for(int j=1;j<=n;j++)//在该行选第几列 
            {
                qizi[hang]=j;
                if(judge(hang))
                {
                    dfs(hang+1);//在本行能下棋的话,就接着下下一行的棋 
                }
            } 
        }
    }
    void cnt(int n)
    {
        dfs(1);//从第一行开始选地方下棋 
    }
    int main()
    {
        for(n=1;n<=10;n++)
        {
            qingkuang=0;
            cnt(n);
            biao[n]=qingkuang;
        }
        int q;
        while(scanf("%d",&q)!=EOF)
        {
            if(q==0)
            break;
            printf("%d
    ",biao[q]);
        }
        return 0;
    }
     
    View Code
                                                Dungeon Master
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 46573   Accepted: 17552

    Description

    You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides. 

    Is an escape possible? If yes, how long will it take? 

    Input

    The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size). 
    L is the number of levels making up the dungeon. 
    R and C are the number of rows and columns making up the plan of each level. 
    Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C.

    Output

    Each maze generates one line of output. If it is possible to reach the exit, print a line of the form 
    Escaped in x minute(s).

    where x is replaced by the shortest time it takes to escape. 
    If it is not possible to escape, print the line 
    Trapped!

    Sample Input

    3 4 5
    S....
    .###.
    .##..
    ###.#
    
    #####
    #####
    ##.##
    ##...
    
    #####
    #####
    #.###
    ####E
    
    1 3 3
    S##
    #E#
    ###
    
    0 0 0
    

    Sample Output

    Escaped in 11 minute(s).
    Trapped!
    一个3维的bfs模板题
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <queue>
    using namespace std;
     
    struct Node{
        int x,y,z;
        int cont;
    };
    char Map[35][35][35];
    int visit[35][35][35];
    int dir[6][3] = {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
    int l,r,c;
    int x1,y1,z1;
     
    void bfs(){
        queue <Node> Q;
        Node t;
        t.x = x1,t.y = y1,t.z = z1,t.cont = 0;
        visit[x1][y1][z1] = 1;
        Q.push(t);
        while(!Q.empty()){
            Node res = Q.front();
            Q.pop();
     
            int xx = res.x;
            int yy = res.y;
            int zz = res.z;
            int Cont = res.cont;
     
            if(Map[xx][yy][zz] == 'E'){     //目标位置且一定最短
                cout<<"Escaped in "<<Cont<<" minute(s)."<<endl;
                return ;
            }
     
            for(int i = 0;i < 6;i ++){      //每一步6个状态
                Node temp;
                int xi = temp.x = xx+dir[i][0];
                int yi = temp.y = yy+dir[i][1];
                int zi = temp.z = zz+dir[i][2];
                temp.cont = Cont+1;
                if(xi < 1 || xi > l || yi < 1 || yi > r || zi < 1 || zi > c)    continue;       //边界判断
                if(Map[xi][yi][zi] != '#' && !visit[xi][yi][zi]){
                    visit[xi][yi][zi] = 1;
                    Q.push(temp);
                }
            }
        }
        cout<<"Trapped!"<<endl;
    }
    int main()
    {
        while(cin>>l>>r>>c){
            if(l == 0 && r == 0 && c == 0)  break;
            for(int i = 1;i <= l;i ++){
                for(int j = 1;j <= r;j ++){
                    for(int k = 1;k <= c;k ++){
                        cin>>Map[i][j][k];
                        if(Map[i][j][k] == 'S')
                            x1 = i,y1 = j,z1 = k;
                    }
                }
            }
            memset(visit,0,sizeof(visit));
            bfs();
        }
        return 0;
    }
    View Code

    Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

    * Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
    * Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

    If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

    Input

    Line 1: Two space-separated integers: N and K

    Output

    Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

    Sample Input

    5 17

    Sample Output

    4
    基础BFS的题目
    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<cstring>
    using namespace std;
    struct point{
        int x,y,step;
    }st;
    int n,m;
    queue<point>q;
    int vst[200000];
    int flag;
    int bfs()
    {
        while(!q.empty())
        {
            q.pop();
        }
        memset(vst,0,sizeof(vst));
        vst[st.x]=1;//标明起始位置;
        q.push(st);
        while(!q.empty())
        {
            point now=q.front();
            if(now.x==m)
            {
                return now.step;//返回当前花费的时间。 
            }
            q.pop();
            for(int j=0;j<3;j++)//每个结点遍历3种情况; 
            {
                point next=now;
                if(j==0)
                {
                    next.x=now.x+1;
                }
                else if(j==1)
                {
                    next.x=now.x-1;
                }
                else if(j==2)
                {
                    next.x=now.x*2;
                }
                next.step++;
                if(next.x==m)
                {
                    return  next.step;
                }
                if(next.x>=0&&next.x<=200000&&!vst[next.x])
                {
                    vst[next.x]=1;
                    q.push(next);
                }
            } 
        }
        return 0;
    }
    int main()
    {
        while(cin>>n>>m)
        {
            st.x=n;
            st.step=0;
            cout<<bfs()<<endl;
        }
        return 0;
    }
    View Code

                           

    Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

    Input

    The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

    Output

    For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

    Sample Input

    2
    6
    19
    0

    Sample Output

    10
    100100100100100100
    111111111111111111
    第一种dfs写法。
    #include<iostream>
    #include<algorithm>
    #define ll long long
    using namespace std;
    int n;int flag;
    void dfs(int x,ll y)
    {
        if(x>19||flag==1)
        {
            return;
        }
        if(y%n==0)
        {
            flag=1;
            cout<<y<<endl;
            return;
        }
        dfs(x+1,y*10);
        dfs(x+1,y*10+1);
    }
    int main()
    {
        while(cin>>n)
        {
            if(!n)
            {
                break;
            }
            flag=0;
            dfs(1,1);
        }
        return 0;
    }
    View Code

       第二种bfs写法。

    # include <stdio.h>
    # include <queue>
    
    using namespace std;
    int m;
    void BFS(long long x)
    {
        queue<long long>Q;
        Q.push(x);
        while(Q.size()) 
        {
            long long  y = Q.front();
            Q.pop();
            if(y%m == 0)
            {
                printf("%lld
    ",y);
                return;
            }
            Q.push(y*10);
            Q.push(y*10+1);
        }
    }
    int main(void)
    {
        while(~scanf("%d",&m),m)
        {
            BFS(1);
        }   
        return 0;
    } 
    View Code

              

    The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. 
    — It is a matter of security to change such things every now and then, to keep the enemy in the dark. 
    — But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know! 
    — I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door. 
    — No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime! 
    — I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds. 
    — Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime. 

    Now, the minister of finance, who had been eavesdropping, intervened. 
    — No unnecessary expenditure, please! I happen to know that the price of a digit is one pound. 
    — Hmm, in that case I need a computer program to minimize the cost. You don't know some very cheap software gurus, do you? 
    — In fact, I do. You see, there is this programming contest going on... Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above. 
    1033 
    1733 
    3733 
    3739 
    3779 
    8779 
    8179
    The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.

    Input

    One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

    Output

    One line for each case, either with a number stating the minimal cost or containing the word Impossible.

    Sample Input

    3
    1033 8179
    1373 8017
    1033 1033

    Sample Output

    6
    7
    0

    题目意思就是从第一个数变成第二个数所需的步骤数并且变化的每个过程中产生的数都必须要是素数。

    #include
    #include
    #include
    #include
    #include
    using namespace std;
     
    mapg;
    bool flag[10000];
    void star()
    {
        for(int i = 1000; i < 10000; i++)
        {
            for(int j = 2; j*j <= i; j++)
                if(i%j == 0)
                {
                    g[i] = 1;
                    break;
                }
        }
    }
     
    struct node
    {
        int x;
        int step;
        node(){}
        node(int xx, int ss)
        {
            x = xx; step = ss;
        }
    };
    queueque;
     
    void bfs(int n, int m)
    {
        while(!que.empty()) que.pop();
        que.push(node(n, 0));
        int a[4];
        memset(flag, 0, sizeof(flag));
        while(!que.empty())
        {
            node tmp = que.front(); que.pop();
            int t = tmp.x;
    //        printf("%d--%d
    ", t, tmp.step);
            for(int i = 0; i < 4; i++)
            {
                a[i] = t%10;
                t /= 10;
            }
            int temp = 1;
            for(int i = 0; i < 4; i++)
            {
                for(int j = 0; j < 10; j++)
                {
                    if(i == 3 && j == 0) continue;
                    if(j == a[i]) continue;
                    int x = tmp.x - a[i]*temp + j*temp;
                    if(x == m) {printf("%d
    ", tmp.step+1);return;}
                    if(!g.count(x) && !flag[x])
                    {
                        que.push(node(x, tmp.step+1));
                        flag[x] = 1;
                    }
                }
                temp *= 10;
            }
        }
    }
     
    int main(void)
    {
        int T;
        star();
        scanf("%d", &T);
        while(T--)
        {
            int n, m;
            scanf("%d%d", &n, &m);
            if(n == m)
            {
                printf("0
    ");
                continue;
            }
            bfs(n, m);
        }
        return 0;
    }
    View Code

     POJ-3087

    已知两堆牌s1和s2的初始状态, 其牌数均为c,按给定规则能将他们相互交叉组合成一堆牌s12,再将s12的最底下的c块牌归为s1,最顶的c块牌归为s2,依此循环下去。给定输入s1和s2的初始状态 以及 预想的最终状态s12。

    #include <stdio.h>
    #include <map>
    #include <string.h>
    #include <string>
    using namespace std;
    int main()
    {
        int n,c,t=0,cut,i;
        scanf("%d",&n);
        while(n--)
        {
            scanf("%d",&c);
            t++;
            cut=0;
            char s1[110],s2[110],s12[220],s[220];
            scanf("%s%s%s",s1,s2,s12);
            map <string,int > map1;
            int len,flat=0;
            while(1)
            {
                cut++;
                len=0;
                for(i=0;i<c;i++)
                {
                    s[len]=s2[i];
                    len++;
                    s[len]=s1[i];
                    len++;
                }
                s[len]='';
                if(strcmp(s,s12)==0)
                {
                    flat=1;
                    break;
                }
                if(map1.find(s)!=map1.end())
                {
                    break;
                }
                map1[s]=0;
                for(i=0;i<c;i++)
                {
                    s1[i]=s[i];
                    s2[i]=s[i+c];
                }
            }
            if(flat)
            {
                printf("%d %d
    ",t,cut);
            }
            else
            {
                printf("%d -1
    ",t);
            }
        }
        return 0;
    }
    View Code

    POJ-3414

    有一个瓶子A和一个瓶子B,可以有三种操作倒满,倒空,或者把瓶子A倒向瓶子B(或者把瓶子B倒向瓶子A),可以扩展出6种操作,没什么简单的写法,只能一种一种的写.....
    当然是使用广搜.......................直到一个瓶子里面有C升水,或者倒不出来这种结果,还需要输出到得步骤, 可以递归输出路径
    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #include<queue>
    using namespace std;
    
    #define maxn 110
    
    int A, B, C;
    char a[10][10] ={ "FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
    
    struct node
    {
        int fromX, fromY, step, op;
    }v[maxn][maxn];
    struct point
    {
        int x, y;
    };//当前瓶子A,B的水量
    
    //输出路径
    void DFS(int x, int y)
    {
        if(x == 0 && y == 0)
            return ;
    
        DFS(v[x][y].fromX, v[x][y].fromY);
    
        printf("%s
    ", a[ v[x][y].op ]);
    
    }
    void BFS()
    {
        queue<point> Q;
        point s, q;
        s.x = s.y = 0;
        v[0][0].step = 1;
    
        Q.push(s);
    
        while(Q.size())
        {
            s = Q.front();Q.pop();
    
            if(s.x == C || s.y == C)
            {
                printf("%d
    ", v[s.x][s.y].step-1);
                DFS(s.x, s.y);
    
                return ;
            }
    
            for(int i=0; i<6; i++)
            {
                q = s;
    
                if(i == 0)
                    q.x = A;
                else if(i == 1)
                    q.y = B;
                else if(i == 2)
                    q.x = 0;
                else if(i == 3)
                    q.y = 0;
                else if(i == 4)
                {
                    if(q.x+q.y <= B)
                        q.y += q.x, q.x = 0;//把A里面的水全倒B里面
                    else
                        q.x -= (B-q.y), q.y = B;//把B倒满
                }
                else
                {
                    if(q.x+q.y <= A)
                        q.x += q.y, q.y = 0;
                    else
                        q.y -= (A-q.x), q.x = A;
                }
    
                if(v[q.x][q.y].step == 0)
                {
                    v[q.x][q.y].step = v[s.x][s.y].step+1;
                    v[q.x][q.y].fromX = s.x;
                    v[q.x][q.y].fromY = s.y;
                    v[q.x][q.y].op = i;
    
                    Q.push(q);
                }
            }
        }
    
        printf("impossible
    ");
    }
    
    int main()
    {
        while(scanf("%d%d%d", &A, &B, &C) != EOF)
        {
            memset(v, 0, sizeof(v));
    
            BFS();
        }
    
       
    View Code

    POJ-3984

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<queue> 
    int dist[10][10];
    int visit[10][10];
    int gra[10][10];
    const int dx[4] = {-1,1,0,0};
    const int dy[4] = {0,0,-1,1};
    using namespace std;
    struct node
    {
        int x,y;
    };
    void bfs(int x,int y)
    {
        int i;
        queue<node>que;
        memset(visit,0,sizeof(visit));
        memset(dist,0,sizeof(dist));
        node n1;
        n1.x = x;
        n1.y = y;
        dist[x][y] = 0;
        que.push(n1);
        visit[x][y] = 1;
        while(!que.empty())
        {
            node n1 = que.front();
            que.pop();
            if((n1.x == 5) && (n1.y == 5))
            {
                //printf("%d
    ",dist[n1.x][n1.y]);
                return ;
            }
            for(i=0; i<4; i++)
            {
                int xx = n1.x + dx[i];
                int yy = n1.y + dy[i];
                if(!visit[xx][yy] && (gra[xx][yy] == 0) && (xx >= 1) && (xx <= 5) &&(yy >= 1) && (yy <= 5))
                {
                    visit[xx][yy] = 1;
                    dist[xx][yy] = dist[n1.x][n1.y] + 1;
                    node n2;
                    n2.x = xx,n2.y = yy;
                    que.push(n2);
                }
            }
        }
    }
    void print_path(node n1,node n2)
    {
        int i;
        if((n2.x == n1.x) && (n1.y == n2.y))
            return;
        for(i=0; i<4; i++)
        {
            int xx = n2.x + dx[i];
            int yy = n2.y + dy[i];
            if((dist[n2.x][n2.y] == dist[xx][yy] + 1) && visit[xx][yy])
            {
                node n3;
                n3.x =xx,n3.y =yy;
                print_path(n1,n3);
                printf("(%d, %d)
    ",n3.x-1,n3.y-1);
            }
        }
        return ;
    }
    int main()
    {
        int i,j;
        for(i=1; i<=5; i++)
            for(j=1; j<=5; j++)
                scanf("%d",&gra[i][j]);
        bfs(1,1);    
        node n1,n2;
        n1.x = 1, n1.y = 1;
        n2.x = 5, n2.y = 5;
        print_path(n1,n2);
        printf("(4, 4)");
        return 0;
    }
    View Code

    Fat brother and Maze are playing a kind of special (hentai) game on an N*M board (N rows, M columns). At the beginning, each grid of this board is consisting of grass or just empty and then they start to fire all the grass. Firstly they choose two grids which are consisting of grass and set fire. As we all know, the fire can spread among the grass. If the grid (x, y) is firing at time t, the grid which is adjacent to this grid will fire at time t+1 which refers to the grid (x+1, y), (x-1, y), (x, y+1), (x, y-1). This process ends when no new grid get fire. If then all the grid which are consisting of grass is get fired, Fat brother and Maze will stand in the middle of the grid and playing a MORE special (hentai) game. (Maybe it’s the OOXX game which decrypted in the last problem, who knows.)

    You can assume that the grass in the board would never burn out and the empty grid would never get fire.

    Note that the two grids they choose can be the same.

    Input

    The first line of the date is an integer T, which is the number of the text cases.

    Then T cases follow, each case contains two integers N and M indicate the size of the board. Then goes N line, each line with M character shows the board. “#” Indicates the grass. You can assume that there is at least one grid which is consisting of grass in the board.

    1 <= T <=100, 1 <= n <=10, 1 <= m <=10

    Output

    For each case, output the case number first, if they can play the MORE special (hentai) game (fire all the grass), output the minimal time they need to wait after they set fire, otherwise just output -1. See the sample input and output for more details.

    Sample Input

    4
    3 3
    .#.
    ###
    .#.
    3 3
    .#.
    #.#
    .#.
    3 3
    ...
    #.#
    ...
    3 3
    ###
    ..#
    #.#

    Sample Output

    Case 1: 1
    Case 2: -1
    Case 3: 0
    Case 4: 2
    #include<stdio.h>
    #include<string.h>
    #include<queue>
    using namespace std;
    #define min(a,b)  (a<b?a:b)
    #define max(a,b)  (a>b?a:b)
    const int INF=0x3f3f3f3f;
    int n,m;
    int vis[15][15];
    char s[15][15];
    int to[4][2]={0,1,0,-1,1,0,-1,0};
    struct node
    {
        int x,y,step;
    }w[100];
    int judge(int x,int y)
    {
        if(x>=0&&y>=0&&x<n&&y<m&&!vis[x][y]&&s[x][y]=='#')
            return 1;
        return 0;
    }
    int bfs(node a,node b)//两点进去同时搜
    {
        queue<node>q;
        q.push(a);
        q.push(b);
        vis[a.x][a.y]=1;
        vis[b.x][b.y]=1;
        int cnt=0;
        while(!q.empty())
        {
            a=q.front();
            cnt=max(cnt,a.step);
            for(int i=0;i<4;i++)
            {
                b.x=a.x+to[i][0],b.y=a.y+to[i][1],b.step=a.step+1;
                if(judge(b.x,b.y))
                {
                    q.push(b);
                    vis[b.x][b.y]=1;
                }
            }
            q.pop();
        }
        return cnt;
    }
    int main()
    {
        int cont=0,t;
        scanf("%d",&t);
        while(++cont<=t)
        {
            int i,j,k,l,sum=0;
            scanf("%d%d",&n,&m);
            for(i=0;i<n;i++)
            {
                scanf("%s",s[i]);
                for(j=0;j<m;j++)
                {
                    if(s[i][j]=='#')
                    {
                        w[sum].x=i,w[sum].y=j,w[sum].step=0;//记录可搜点的坐标
                        sum++;
                    }
                }
            }
            if(sum<=2)
                printf("Case %d: 0
    ",cont);
            else
            {
                int ans=INF;
                for(i=0;i<sum;i++)
                {
                    for(j=i;j<sum;j++)
                    {
                        memset(vis,0,sizeof(vis));
                        int cnt=bfs(w[i],w[j]);//两点BFS
                        int flag=0;
                        for(k=0;k<n;k++)
                        {
                            for(l=0;l<m;l++)
                            {
                                if(s[k][l]=='#'&&!vis[k][l])//判断是否剩下没有点燃的草
                                {
                                    flag=1;
                                    break;
                                }
                            }
                            if(flag)
                                break;
                        }
                        if(!flag)//全部烧完,则求最短时间
                            ans=min(ans,cnt);
                    }
                }
                if(ans==INF)
                    printf("Case %d: -1
    ",cont);
                else
                    printf("Case %d: %d
    ",cont,ans);
            }
        }
        return 0;
    }
    View Code

    UVA - 11624

    The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid. 

    InputThe input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket. 
    OutputFor each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets. 
    Sample Input

    1 1
    *
    3 5
    *@*@*
    **@**
    *@*@*
    1 8
    @@****@*
    5 5 
    ****@
    *@@*@
    *@**@
    @@@*@
    @@**@
    0 0 

    Sample Output

    0
    1
    2
    2
    #include <stdio.h>
    char a[111][111];
    int dir[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
    int m, n;
    int flag;
    int dfs(int x, int y)
    {
        if(a[x][y]=='*')
            return flag;
        flag=1;
        a[x][y]='*';//记得标记,这样不会重复计数
        int tx,ty;
        for(int i=0;i<8;i++)
        {
            tx=x+dir[i][0];
            ty=y+dir[i][1];
            if(tx>=0&&tx<m&&ty>=0&&ty<n)
                dfs(tx,ty);
        }
        return flag;
    }
    int main()
    {
        while(~scanf("%d %d",&m,&n)&&m+n)
        {
            int num=0;
            for(int i=0;i<m;i++)
                scanf("%s",a[i]);
            for(int i=0;i<m;i++)
            {
                for(int j=0;j<n;j++)
                {//把每个点都进去搜索一遍
                    flag=0;
                    if(dfs(i,j))
                    {
                        num++;
                    }
                }
            }
            printf("%d
    ",num);
        }
    }
    View Code
     
     
    大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但
    seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

    Input三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。Output如果能平分的话请输出最少要倒的次数,否则输出"NO"。Sample Input

    7 4 3
    4 1 3
    0 0 0

    Sample Output

    NO
    3
    #include <queue>
    #include <cstring> //用来给数组赋初值为0的,memset;
    using namespace std;
    int b[3],book[101][101][101],half;
    struct node
    {
        int cur[3],s;          //cur表示现在瓶子里的水,b表示水的容量
    }p,temp;          //p获取当前的“head”,temp用于6个动作的记录。
    void bfs()
    {
        queue<node> q;         //声明一个队列,由于经常做pat乙  只有一组数据习惯声明全局变量,如果把这句放在bfs()外边,因为有多组
        p.cur[0]=b[0];          //测试数据,如果不把之前队列里的数据清空就会带到下一组测试中(做题考虑下这个机制会不会对某些题目有用)
        p.cur[1]=p.cur[2]=p.s=0;  //放到bfs里面  每次队列都是新的。
        q.push(p);                  //将最开始状态初始化 加入队列q中;
        while(!q.empty())
        {
            p=q.front();
            q.pop();
            for(int i=0;i<3;i++)     //控制哪个杯子往外倒水
            {
                if(p.cur[i]>0)      //如果有水才可以给别的倒水。
                {
                    for(int j=0;j<3;j++)   //接受水的杯子
                    {
                        temp=p;            //这很重要!之前没加这句一直wa,因为这6个动作是”平行“的,即都是从前一步状态开始的,如果没有
                        if(i==j)  continue ;   //这一句,就不是平行的,相互叠加的。这个很重要!
                        if(temp.cur[i]>b[j]-temp.cur[j])   //判断能不能倒满了,这是可以倒满的情况
                        {
                            temp.cur[i]-=b[j]-temp.cur[j];      //这两句话一定不要颠倒,之前因为这个一直不出答案,先运算后赋值。。。
                            temp.cur[j]=b[j];
                        }
                        else     // 不可以倒满的情况
                        {
                            temp.cur[j]+=temp.cur[i];
                            temp.cur[i]=0;
                        }
                        if(!book[temp.cur[0]][temp.cur[1]][temp.cur[2]])  //判断这种情况是否出现过
                        {
                            book[temp.cur[0]][temp.cur[1]][temp.cur[2]]=1;  //标记为出现过,说明这一步“有效”,step+1;
                            temp.s++;
                            if((temp.cur[0]==half&&temp.cur[1]==half)||(temp.cur[0]==half&&temp.cur[2]==half)||(temp.cur[1]==half&&temp.cur[2]==half))
                                {
                                    cout << temp.s << endl;  // step里的每一个“动作”都要判断是否符合条件,因为这动作是平行的 所以放在内循环里面!
                                    return ;             //直接跳出bfs
                                }
                                q.push(temp);// 如果不是所求,就把他加到队列里。之后在从每一个“动作调用”
                        }
                    }
                }
            }
     
     
        }
          cout <<"NO"<<endl;  //如果整个循环结束还是没有找到说明不可以平分;
    }
    int main()
    {
        while(cin >> b[0]>>b[1]>>b[2],b[0]+b[1]+b[2])   //如果相加都等于0 即000 用于结束
        {
            memset(book,0,sizeof(book));  //多组数据每一组都要赋初值,想用book【】【】={0},必须要在声明book数组时候用;
            book[b[0]][b[1]][b[2]]=1;   //把初始点标记来过,这一点在调用bfs之前做 很多题都要注意这一点。
            if(b[0]%2)  cout << "NO"<<endl;
            else {half=b[0]/2;bfs();}
        }
        return 0;
    }
    View Code
    Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki. 
    Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest. 
    Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes. 

    InputThe input contains multiple test cases. 
    Each test case include, first two integers n, m. (2<=n,m<=200). 
    Next n lines, each line included m character. 
    ‘Y’ express yifenfei initial position. 
    ‘M’    express Merceki initial position. 
    ‘#’ forbid road; 
    ‘.’ Road. 
    ‘@’ KCF 
    OutputFor each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.Sample Input

    4 4
    Y.#@
    ....
    .#..
    @..M
    4 4
    Y.#@
    ....
    .#..
    @#.M
    5 5
    Y..@.
    .#...
    .#...
    @..M.
    #...#

    Sample Output

    66
    88
    66
    // 664.cpp : 定义控制台应用程序的入口点。
    //
     
    #include "stdafx.h"
     
     
    #include<cstdio>
    #include<cstring>
    #include<queue>
    #define INF 0x3f3f3f3f
    #define MAX 210
    #define MEM(arr,w) memset(arr,w,sizeof(arr));
    using namespace std;
    struct node
    {
        int x,y;
    }st1,st2,ss,tt;
    int dir[4][2]={0,1,1,0,0,-1,-1,0};
    int n,m,MAXT;
    char map[MAX][MAX];
    int visit[MAX][MAX];
    int step1[MAX][MAX],step2[MAX][MAX];
    void Init()
    {
        MEM(visit,false);
        MAXT=INF;
        MEM(step1,0);
        MEM(step2,0);
    }
    void BFS(node st,int step[][210])
    {
        queue<node> Q;
        Q.push(st);
        visit[st.x][st.y]=true;
        while(!Q.empty())
        {
            ss=Q.front();
            Q.pop();
            for(int i=0;i<4;i++)
            {
                tt.x=ss.x+dir[i][0];
                tt.y=ss.y+dir[i][1];
                if(tt.x>=0&&tt.x<n&&tt.y>=0&&tt.y<m&&map[tt.x][tt.y]!='#'&&!visit[tt.x][tt.y])//最基本的条件必须符合
                {
                    step[tt.x][tt.y]=step[ss.x][ss.y]+1;
                    visit[tt.x][tt.y]=true;
                    Q.push(tt);
                }
            }
        }
        return ;
    }
    int main()
    {
        int i,j;
        while(scanf("%d%d",&n,&m)!=EOF)
        {
            for(i=0;i<n;i++)
            {
                scanf("%s",map[i]);
                for(j=0;j<m;j++)
                {
                    if(map[i][j]=='Y') st1.x=i,st1.y=j;
                    if(map[i][j]=='M') st2.x=i,st2.y=j;
                }
            }
            Init();
            BFS(st1,step1);
            MEM(visit,false);
            BFS(st2,step2);
            for(i=0;i<n;i++)
                for(j=0;j<m;j++)
                    if(map[i][j]=='@'&&step1[i][j]!=0&&step2[i][j]!=0)
                        if(step1[i][j]+step2[i][j]<MAXT) MAXT=step1[i][j]+step2[i][j];
            printf("%d
    ",MAXT*11);
     
        }
    }
     
    View Code
  • 相关阅读:
    Linux下Nginx配置文件nginx.conf默认位置修改
    centos下安装Nginx
    让网站永久拥有免费HTTPS(SSL)
    Perl深度优先迷宫算法
    Perl字符贪吃蛇
    Linux静态路由配置
    Linux虚拟机网络配置
    Perl快速查找素数
    Shell同步数据到oracle数据库
    Shell修改密码为原密码
  • 原文地址:https://www.cnblogs.com/txrtyy/p/9274729.html
Copyright © 2011-2022 走看看