POJ2802小游戏

题目描述:
读入一个矩阵,0表示可以通过,1表示不可以通过,矩阵周围的一圈也可以通过。任意给两个点A,B,判断是否能从A到达B,若能到达,输出所有路径中拥有折线段数最少的那个。
别人的程序:
想法是DFS+剪枝,用方向的改变次数来计算折线段数。DFS函数参数为:本次访问的点,已有的折线段数,方向。

  1. 在函数的开始判断是否当前路径的折线段数已经超过了最少的那条(剪枝),超过则返回。
  2. 然后判断是否到达了终点,由于比当前更长的路径已经返回了,所以能到达终点的路径的折线段数一定是最短的,直接记录并返回即可。
  3. 然后依次访问四个方向,在进入之前判断是否在界限内,是否可以走且未被访问过,或者是最后一个点(因为最后一个点实际上是不允许通行的,不然就无法到达终点了)
  4. 若能访问,则标记这个点被访问过,访问(进入递归函数),恢复这个点为未被访问过(因为要求的是最优解,可能有多条路径,之后还会访问这个点)
  5. 这种写法进入第一个点时是不需要判断的,一定可以进入。
#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){
            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))){
                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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值