武士风度的牛(暴力广搜)

来源:互联网 发布:象棋软件有哪些 编辑:程序博客网 时间:2024/06/10 17:36

此题为纯广搜~~可提高对广搜的理解。

Description

农民John有很多牛,他想交易其中一头被Don称为The Knight的牛。这头牛有一个独一无二的超能力,在农场里像Knight一样地跳(就是我们熟悉的象棋中马的走法)。虽然这头神奇的牛不能跳到树上和石头上,但是它可以在牧场上随意跳,我们把牧场用一个x,y的坐标图来表示。
这头神奇的牛像其它牛一样喜欢吃草,给你一张地图,上面标注了The Knight的开始位置,树、灌木、石头以及其它障碍的位置,除此之外还有一捆草。现在你的任务是,确定The Knight要想吃到草,至少需要跳多少次。The Knight的位置用'K'来标记,障碍的位置用'*'来标记,草的位置用'H'来标记。

这里有一个地图的例子:
11 | . . . . . . . . . .
10 | . . . . * . . . . . 
9 | . . . . . . . . . . 
8 | . . . * . * . . . . 
7 | . . . . . . . * . . 
6 | . . * . . * . . . H 
5 | * . . . . . . . . . 
4 | . . . * . . . * . . 
3 | . K . . . . . . . . 
2 | . . . * . . . . . * 
1 | . . * . . . . * . . 
0 ----------------------

0 1 2 3 4 5 6 7 8 9 0 

The Knight 可以按照下图中的A,B,C,D...这条路径用5次跳到草的地方(有可能其它路线的长度也是5):
11 | . . . . . . . . . .
10 | . . . . * . . . . .
9 | . . . . . . . . . .
8 | . . . * . * . . . .
7 | . . . . . . . * . .
6 | . . * . . * . . . F<
5 | * . B . . . . . . .
4 | . . . * C . . * E .
3 | .>A . . . . D . . .
2 | . . . * . . . . . *
1 | . . * . . . . * . .
0 ----------------------
1
0 1 2 3 4 5 6 7 8 9 0

Input

第一行: 两个数,表示农场的列数(<=150)和行数(<=150)

第二行..结尾: 如题目描述的图。

Output

一个数,表示跳跃的最小次数。

Sample Input

10 11
..........
....*.....
..........
...*.*....
.......*..
..*..*...H
*.........
...*...*..
.K........
...*.....*
..*....*..

Sample Output

5
#include <iostream>#include <stdio.h>#include <queue>#include <string.h>using namespace std; typedef struct{    int x, y;    int step;}Point; int m ,n;char map[150][150];int mark[150][150];Point sta, e, cur, ne;int dir[8][2] = {{-1,-2},{1,-2},{-1,2},{1,2},{-2,-1},{2,-1},{-2,1},{2,1}};//8个方向queue<Point>q; int bfs(); int main(){    int i, j, step;    scanf("%d%d",&m,&n);    getchar();//此处getchar()不可省,否则坑爹    for(i=0; i<n; i++)    {        scanf("%s",map[i]);        for(j=0; j<m; j++)        {            if(map[i][j] == 'K')            {                sta.x = i;                sta.y = j;            }            if(map[i][j] == 'H')            {                e.x = i;                e.y = j;            }        }    }    step = bfs();    printf("%d\n",step);    return 0;} int bfs(){    int i;    while(!q.empty())//初始化队列        q.pop();    sta.step = 0;    mark[sta.x][sta.y] = 1;    q.push(sta);     while(!q.empty())    {        cur = q.front();        q.pop();         if(cur.x == e.x && cur.y == e.y)            return cur.step;        for(i=0; i<8; i++)        {            ne.x = cur.x + dir[i][0];            ne.y = cur.y + dir[i][1];            ne.step = cur.step + 1;            if(ne.x >= 0 && ne.x < n && ne.y >= 0 && ne.y < m &&                 map[ne.x][ne.y] != '*' && mark[ne.x][ne.y] == 0)            {                q.push(ne);                mark[ne.x][ne.y] = 1;            }        }    }}