程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> C語言BFS

C語言BFS

編輯:關於C
Problem Description 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.

Input The 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

Output For 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

大概題意:輸入地圖, # :表示牆 . :表示路 YM :表示兩個人 @ :表示KFC. 兩個人都要去同一家KFC,但是地圖上有很多KFC,輸出最短的路程和.(注:每步的路程是11)

思路:以兩個人為基准點先後BFS,每次找到KFC的位置後,在新開的一個數組(ans)中對應的地方記錄路程,最後遍歷ans中最小的便是最短路程.
#include 
#include 
char map[211][211];     //地圖
int book[211][211];    //標記數組
int ans[211][211];     //記錄距離的數組
int a[4][2]={1,0,-1,0,0,1,0,-1},m,n;
struct Team
{
    int x,y,s;
}que[100000];
void bfs(int startx,int starty)
{
    int head,tail;
    int tx,ty,i;
    head=tail=0;
    que[tail].x=startx;
    que[tail].y=starty;
    que[tail++].s=0;
    book[startx][starty]=1;
    while(head=n||ty<0||ty>=m||book[tx][ty]||map[tx][ty]=='#')
                continue;
            if(map[tx][ty]=='@')
                ans[tx][ty]+=que[head].s+1;   //在ans記錄路程.
            book[tx][ty]=1;
            que[tail].x=tx;
            que[tail].y=ty;
            que[tail++].s=que[head].s+1;
        }
        head++;
    }
}
int main()
{
    int i,j,min=99;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(ans,0,sizeof(ans));
        memset(book,0,sizeof(book));
        for(i=0;i








  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved