最少行走步数 bfs dfs 求法

本文探讨了骑士在棋盘上从一点移动到另一点所需的最少步数问题,使用宽度优先搜索(BFS)算法实现了高效的解决方案,并对比了深度优先搜索(DFS)的效率,通过具体题目实例展示了算法的应用。

//bfs求最小行走步数模板题

TOJ-2481: Knight Moves

描述

Background 
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him? 
The Problem 
Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov. 
For people not familiar with chess, the possible knight moves are shown in Figure 1. 

 

输入

The input begins with the number n of scenarios on a single line by itself. 
Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 <= l <= 300). The entire board has size l * l. The second and third line contain pair of integers {0, ..., l-1}*{0, ..., l-1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario.

输出

For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,distance is zero. The distance must be written on a single line.

样例输入

 

3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1

样例输出

 

5
28
0

#include<bits/stdc++.h>
using namespace std;
int a,b,c,d,size1;
int drec[9][2]={{-2,1},{-2,-1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}}//走动方式;
const int N=310;
int vis[N][N];
struct node
{
    int x,y,step;
    node(){}
    node(int x1,int y1,int step1):x(x1),y(y1),step(step1){}
};
void bfs(int x,int y)
{
  memset(vis,0,sizeof(vis));
  vis[x][y]=1;
  queue<node> q;
  q.push(node(x,y,0));
  while(!q.empty())
  {
      node a=q.front();
      q.pop();
      for(int i=0;i<8;i++)
      {
          int xx=a.x+drec[i][0];
          int yy=a.y+drec[i][1];
           if(xx>=0&&xx<size1&&yy>=0&&yy<size1&&(vis[xx][yy]==0))//可以行走的条件
            {
                vis[xx][yy]=1;
                q.push(node(xx,yy,a.step+1));
                if(xx==c&&yy==d)
                    {
                    cout<<a.step+1<<endl;
                    return;
                    }
            }
       }
    }
}
int main()
{
  int t ;
  cin>>t;
  while(t--)
  {
      cin>>size1;
      cin>>a>>b>>c>>d;
      if(a==c&&d==b)
      {
          cout<<0<<endl;
          continue;
      }
      bfs(a,b);
  }
}

 

//bfs 相对于 dfs 来说走的少了很多所以时间上也更快一点,因为dfs要走出所有的路,bfs只是同时在每一条路上走出一步;

下面是dfs 代码 如果用dfs代码题交这个题是超时的;

 

#include<bits/stdc++.h>
using namespace std;
int a,b,c,d,size1;
int drec[9][2]={{-2,1},{-2,-1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
const int N=301;
int vis[N][N];
int viss[N][N];
int minn=100000;
void dfs(int x,int y,int step)
{
    if(step>=viss[x][y]||step>=minn)
        return;
    viss[x][y]=step;
    for(int i=0;i<8;i++){
        int xx=x+u[i][0];
        int yy=y+u[i][1];
        if(xx>=0&&xx<=size1&&yy>=0&&yy<=size1&&(!vis[xx][yy])){
            if(xx==c&&yy==d){
                minn=min(step+1,minn);
         return ;
            }
            vis[xx][yy]=1;
            dfs(xx,yy,step+1);
            vis[xx][yy]=0;
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
    minn=1000000;
    cin>>size1;
    cin>>a>>b>>c>>d;
    if(a==c&&b==d)
    {
         cout<<0<<endl;
         continue;
    }
    memset(viss,0x3f3f3f3f,sizeof(viss));
    dfs(a,b,0);
    cout<<minn<<endl;
    }
}

 

 

转载于:https://www.cnblogs.com/xbqdsjh/p/11503136.html

### 深度优先搜索算法详解 深度优先搜索(Depth-First Search,简称 DFS)是一种用于遍历或搜索树或图结构的经典算法。其核心思想是从某个起点出发,沿着某一条路径深入探索直到不能再前进为止,随后回溯至上一个分支点继续探索其他可能的路径[^1]。 #### 特性描述 DFS 的特性在于它的递归性质以及栈式的操作模式。具体来说,当遇到新的未访问节点时,DFS 将该节点标记为已访问并将其压入调用栈中进一步处理;如果当前节点无任何可扩展的新邻接点,则返回至最近的一个具有未访问邻居的节点处重新尝试延伸新路径[^2]。 以下是实现此逻辑的一种典型 Python 实现: ```python def dfs(graph, start): visited = set() # 创建集合存储已经访问过的节点 def helper(node): if node not in visited: # 如果节点尚未被访问过 visited.add(node) # 添加到visited集中表示已被访问 for neighbor in graph[node]: # 遍历相邻节点列表中的每一个元素 helper(neighbor) # 对于每个未访问的邻居执行同样的递归过程 helper(start) # 调用辅助函数从起始顶点开始进行dfs return list(visited) # 返回最终得到的所有访问顺序作为结果集 ``` 这段代码展示了如何通过递归来完成整个图或者子图上的完全遍历工作流程[^1]。 #### 经典例题解析——迷宫最短路径问题 给定一个二维数组代表的地图 grid ,其中 '0' 表示可以通过的位置,'1' 则意味着障碍物不可通行。现在假设我们位于左上方坐标 (0,0),问能否到达右下角位置(n−1,m−1)? 若可以则输出最少步数; 否则输出 -1. 解决这个问题需要用到 BFSDFS 方法来模拟行走的过程。这里采用的是基于 DFS 的解决方案: ```python class Solution(object): def shortestPathBinaryMatrix(self, grid): n=len(grid) if grid[0][0]==1 or grid[n-1][n-1]==1:return -1 directions=[(-1,-1), (-1,0), (-1,+1), (0,-1),(0,+1), (+1,-1),(+1,0),(+1,+1)] stack=[((0,0),1)] ; seen={(0,0)} while stack: pos,dist=stack.pop() if pos==(n-1,n-1):return dist x,y=pos for dx,dy in directions: nx=x+dx;ny=y+dy; if 0<=nx<n and 0<=ny<n and grid[nx][ny]==0 and (nx,ny)not in seen : seen.add((nx,ny)) stack.append(((nx,ny),dist+1)) return -1 ``` 在这个例子当中,虽然理论上也可以利用 DFS 来求解最短距离的问题,但实际上因为缺乏剪枝机制等原因使得效率远不如 BFS 。因此实际应用中应视具体情况灵活选用合适的方法[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值