zju 1671 Walking Ant

本文介绍了一种使用记忆化搜索的经典搜索算法实现,并通过特定条件优化了搜索过程的速度。该算法在进行宽度优先搜索(BFS)时,仅在当前点的生命值高于目标点的生命值时继续搜索,以此来减少不必要的计算步骤。

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

依然是经典搜索,+了记忆化,速度快了不少.即在bfs的过程中,只有当当前点的hp>目标点的hp时,才走这一步.
#include <iostream>
#include 
<string>
#include 
<queue>
using namespace std;
int dir[4][2= {{0,1},{0,-1},{1,0},{-1,0}};
int m, n;
int Map[101][101];
int dp[101][101];
int sx, sy, ex, ey;

typedef 
struct  
{
    
int x,y;
    
int hp;
    
int cnt;
}
Point;

int main()
{
    
int i, j;
    Point s, t, tt;
    
while (cin >> n >> m)
    
{
        
if(n==0 && m==0)
            
break;
        
for (i=0; i<m; ++i)
        
{
            
for (j=0; j<n; ++j)
            
{
                cin 
>> Map[i][j];
                
if(Map[i][j] == 2)
                    sx 
= i, sy = j;
                
if (Map[i][j] == 3)
                    ex 
= i, ey = j;
            }

        }

        
bool flag = false;
        memset(dp, 
0sizeof(dp));
        s.x 
= sx, s.y = sy, s.cnt = 0, s.hp = 6, dp[sx][sy] = 6;
        queue
<Point> mq;
        mq.push(s);
        
while (!mq.empty())
        
{
            t 
= mq.front();
            mq.pop();

            
if(t.x==ex && t.y==ey && t.hp>0)
            
{
                flag 
= true;
                
break;
            }

            
if(t.hp <= 1)
                
continue;
            
for (i=0; i<4++i)
            
{
                
int x = t.x + dir[i][0];
                
int y = t.y + dir[i][1];

                
if(x>=0&&x<&& y>=0&&y<&& Map[x][y]!=0)
                
{
                    
if(dp[x][y] < dp[t.x][t.y])
                    
{
                        
if(Map[x][y] == 4)
                            dp[x][y] 
= 6;
                        
else
                            dp[x][y] 
= dp[t.x][t.y]-1;
                        tt.x 
= x;
                        tt.y 
= y;
                        tt.hp 
= dp[x][y];
                        tt.cnt 
= t.cnt+1;
                        
if(tt.hp > 0)
                            mq.push(tt);
                    }

                    
                }

            }

        }

        
if(!flag)
            cout 
<< "-1";
        
else
            cout 
<< t.cnt;
        cout 
<< endl;
        

    }

    
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值