1251:仙岛求药

bfs基础题  当然 你也可以用dfs做   记得每次地图清空      

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <bitset>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <map>
#include <set>
#include<iomanip>
#include <bits/stdc++.h>
/***************************************/
#define  ll  long long
#define int64 __int64
#define PI 3.1415927
#define INF 99999
const int maxn = 2010;
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
int dir8[][2]={{-2,1},{-2,-1},{-2,2},{-2,-2},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1},{2,-2},{2,2}};
int dir4[4][2]={{-1,0},{1,0},{0,-1},{0,1}};


char mp[310][110];
int n,m;
int vis[310][310];
struct node {
int x,y;
int step;
};int ans=99999999;

 void bfs(node st)
 {
    queue<node>q;
    vis[st.x][st.y]=1;
    q.push(st);

     while(!q.empty())
     {
         node cur=q.front();
         q.pop();
         if(mp[cur.x][cur.y]=='*')
         {
             ans=cur.step;

             return ;
         }

         for(int i=0;i<4;i++)
         {
              node nx;nx.x=cur.x+dir4[i][0];nx.y=cur.y+dir4[i][1];


              if(nx.x<0||nx.y<0||nx.x>n||nx.y>m||vis[nx.x][nx.y]||mp[nx.x][nx.y]=='#')continue;

              vis[nx.x][nx.y]=1;
              nx.step=cur.step+1;
              q.push(nx);
         }






     }



 }





int main()
{

while(cin>>n>>m&&(n&&m))

{
    memset(vis,0,sizeof(vis));
    memset(mp,'#',sizeof(mp));
    node st;
 for(int i=0;i<n;i++)
 for(int j=0;j<m;j++){

    cin>>mp[i][j];
    if(mp[i][j]=='@')
    {
        st.x=i;st.y=j;st.step=0;

    }
 }
ans=99999;
 bfs(st);
if(ans>=999) cout<<-1<<endl;

else
     cout<<ans<<endl;
}


   return 0;
}

 

### 关于仙岛的DFS算法实现与解析 #### 什么是深度优先搜索(DFS) 深度优先搜索(Depth First Search, DFS)是一种用于图或树结构遍历的方法。它从某个起点出发,沿着一条路径尽可能深入探索,直到无法继续为止,随后回溯并尝试其他可能的路径[^2]。 对于“仙岛”这一经典问,可以将其抽象为在一个二维网格上找到从起始位置到达目标位置的所有可行路径。此过程可以通过DFS来完成。 #### 数据表示 假设地图是一个二维数组 `grid`,其中: - `0` 表示可通过的位置; - `1` 或其他特定值表示障碍物不可通过; - 起点和终点分别由坐标 `(start_x, start_y)` 和 `(end_x, end_y)` 给定。 为了防止重复访问同一节点,在实际编程中通常会引入一个辅助矩阵 `visited` 来记录哪些位置已经被访问过。 #### 算法核心逻辑 以下是基于递归方式实现的DFS伪代码描述: ```python def dfs(x, y): # 如果超出边界或者遇到障碍物,则停止进一步探索 if not (0 <= x < rows and 0 <= y < cols) or grid[x][y] != 0: return False # 判断是否已经抵达目的地 if (x, y) == (end_x, end_y): return True # 将当前位置标记为已访问 visited[x][y] = True # 定义四个方向向量:上下左右移动 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 遍历每一个可能的方向 for dx, dy in directions: nx, ny = x + dx, y + dy # 只有当新位置尚未被访问时才进入下一层递归 if not visited[nx][ny]: if dfs(nx, ny): # 若某条路成功则返回True return True # 当前路径无解,恢复状态以便后续尝试别的分支 visited[x][y] = False return False ``` 上述函数实现了基本的功能框架,但具体应用还需要考虑更多细节比如输入读取、初始化参数设置以及最终输出结果处理等问[^3]。 #### Python完整版代码实例 下面给出一段完整的Python程序作为参考: ```python # 初始化变量 rows, cols = map(int, input().split()) # 获取行列数 grid = [] for _ in range(rows): row = list(map(int, input().strip())) grid.append(row) start_x, start_y = map(int, input().split()) end_x, end_y = map(int, input().split()) # 创建访问标志表 visited = [[False]*cols for _ in range(rows)] directions = [(0, 1),(1, 0),(0,-1),(-1,0)] found_path = [] def findPath(x,y,path=[]): global found_path if not(0<=x<rows and 0<=y<cols)or grid[x][y]==1 or visited[x][y]: return path.append((x,y)) if (x==end_x and y==end_y): found_path=path.copy() else: visited[x][y]=True for d in directions: new_x,new_y=x+d[0],y+d[1] findPath(new_x,new_y) findPath(start_x,start_y) if found_path: print("Path Found:",'->'.join([f"({a},{b})"for a,b infound_path])) else : print("No Path Exists.") ``` 注意这里我们定义了一个全局列表存储发现的第一条合法路径,并且每次调用之前都需要清空该列表以防干扰新的查询操作[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值