HDOJ1010 解题报告

本文探讨了一种在限定时间内通过迷宫并找到宝藏的算法解决方案。迷宫由墙壁、起点、终点和空地组成,算法通过深度优先搜索(DFS)策略,结合步长优化和奇偶优化技巧,实现快速定位宝藏位置。同时,文章讨论了迷宫大小、宝藏出现时间和路径长度之间的关系,以及如何判断在给定时间内能否找到宝藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://www.cnblogs.com/peng-come-on/archive/2012/01/20/2327793.html。

一、输入解释

The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:

'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.

The input is terminated with three 0's. This test case is not to be processed.

T is time limit.

二、源代码

#include<iostream>
#include<math.h>
using namespace std;

char map[10][10];
int N,M,T;
int di,dj,escape;
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};//左右下上四个方向 

void dfs(int x,int y,int cnt)
{
      if(x>N || y>M || x<1 || y<1 )
          return;
      if(cnt==T && x==di && y==dj)
          escape=1;
      if(escape==1)//没有这一句会导致超时 
          return;
      int temp=(T-cnt)-abs(x-di)-abs(y-dj);//
      if(temp<0||temp&1) ////步长优化与奇偶优化
          return; 
      for(int i=0;i<4;i++)
      {
          if(map[x+dir[i][0]][y+dir[i][1]]!='X')
          {
              map[x+dir[i][0]][y+dir[i][1]]='X';
              dfs(x+dir[i][0],y+dir[i][1],cnt+1);
              map[x+dir[i][0]][y+dir[i][1]]='.';//回退
          }
      }
      return;
}
int main()
{
while(1)
      {
          int wall=0;
          cin>>N>>M>>T;
          if(N==0 && M==0 && T==0)
              break;
          int si,sj;
          for(int i=1;i<=N;i++)
              for(int j=1;j<=M;j++)
              {
                  cin>>map[i][j];
                  if(map[i][j]=='S')
                  {      
                      si=i;sj=j;
                  }
                  else if(map[i][j]=='D')
                  {
                      di=i;dj=j;
                  }
                  else if(map[i][j]=='X')
                      wall++;
              }
          if(T>=M*N-wall)
          {      
              cout<<"NO"<<endl;
              continue;
          }
          map[si][sj]='X';
          escape=0;
          dfs(si,sj,0);
          if(escape==1)
              cout<<"YES"<<endl;
          else
              cout<<"NO"<<endl;
      }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值