Problem 10:武士风度的牛

来源:互联网 发布:珠江台直播软件 编辑:程序博客网 时间:2024/06/10 06:35

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 ----------------------1 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 ----------------------10 1 2 3 4 5 6 7 8 9 0Input第一行: 两个数,表示农场的列数(<=150)和行数(<=150)第二行..结尾: 如题目描述的图。Output一个数,表示跳跃的最小次数。Sample Input10 11..............*..................*.*...........*....*..*...H*............*...*...K...........*.....*..*....*..Sample Output5Hint搜索练习



Codes:

#include<iostream>#include <string.h>#include <queue>#include <stdio.h>using namespace std;#define max 150int visit[max][max];char a[max][max];int col, row;typedef struct {    int x;    int y;    int step;//步数} Farm;Farm cow;//牛int targetx, targety;//草的位置//方向int movy[] = {-1,1,2,2,1,-1,-2,-2};//控制列int movx[] = {-2,-2,-1,1,2,2,1,-1};//控制行int check(Farm curr) {    if(curr.x == targetx && curr.y == targety)        return 1;    return 0;}int bfs() {    int i, j;    queue <Farm> ss;    cow.step = 0;    ss.push(cow);    visit[cow.x][cow.y] = 1;;//广搜    while(!ss.empty()) {        Farm temp = ss.front();        ss.pop();        if(check(temp))            return temp.step;                for(i=0; i<8; i++) {            temp.x += movx[i];            temp.y += movy[i];            if(!visit[temp.x][temp.y] && a[temp.x][temp.y]!='*' && temp.x>=0&&temp.x<row && temp.y>=0&&temp.y<col) {                visit[temp.x][temp.y] = 1;                Farm newT = temp;                newT.step = temp.step + 1;                ss.push(newT);            }            temp.x -= movx[i];            temp.y -= movy[i];        }    }} int main(void) {    int i, j;    scanf("%d%d", &col, &row);    getchar();    for(i=0; i<row; i++) {        for(j=0; j<col; j++) {            scanf("%c", &a[i][j]);            if(a[i][j] == 'K') {                cow.x = i;                cow.y = j;            }            else if(a[i][j] == 'H') {                targetx = i;                targety = j;            }           }        getchar();    }    memset(visit, 0, sizeof(visit));    printf("%d\n", bfs());        return 0;}



原创粉丝点击