北大 算法 2.2 递归 小游戏




#include <iostream>
#include <stdio.h>
using namespace std;
#include <memory.h>
#define MAXIN 75

char board[MAXIN+2][MAXIN+2];
int minstep,w,h,to[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
bool mark[MAXIN+2][MAXIN+2];

void Search(int now_x,int now_y,int end_x,int end_y,int step,int f){
    if(step>minstep) return;
    if(now_x == end_x && now_y == end_y){
        if(minstep>step){
            minstep = step;
            return;
        }
    }
    for(int i = 0;i<4;i++){
        int x = now_x + to[i][0];
        int y = now_y + to[i][1];
        if( ((x>-1) && (x<w+2) && (y>-1) && (y<h+2))
           &&((board[y][x] == ' ' && mark[y][x] == false)||(x == end_x&&y==end_y&&board[y][x]=='X'))){
                mark[y][x] = true;
                if(f==i) Search(x,y,end_x,end_y,step,i);
                else Search(x,y,end_x,end_y,step+1,i);
                mark[y][x] = false; //回溯,该位置未曾走过
           }
    }
}

int main(){
    int Boardnum = 0;
    while(scanf("%d %d",&w,&h)){
        if(w==0 && h == 0) break;
        Boardnum++;
        printf("Board #%d:\n",Boardnum);
        int i,j;
        for(i=0;i<MAXIN+2;i++){
            board[0][i] = board[i][0] = ' ';
        }
        for(i=1;i <= h;i++){
            getchar();
            for(j=1;j<=w;j++) board[i][j] = getchar();
        }
        for(i=0;i<=w;i++)
            board[h+1][i+1] = ' ';
        for(i=0;i<=h;i++)
            board[i+1][w+1] = ' ';
        int begin_x,begin_y,end_x,end_y,count = 0;
        while(scanf("%d %d %d %d",&begin_x,&begin_y,&end_x,&end_y)&&begin_x > 0   ){
            count++;
            minstep = 100000;
            memset(mark,false,sizeof(mark));
            Search(begin_x,begin_y,end_x,end_y,0,-1);
            if(minstep<100000) printf("Pair %d: %d segments.\n",count,minstep);
            else printf("Pair %d: impossible.\n",count);
        }
        printf("\n");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值