dfs与bfs伪代码

首先是bfs

#include<cstdio>  
#include<cstring>  
#include<queue>  
#include<algorithm>  
using namespace std;  
const int maxn=100;  
bool vst[maxn][maxn]; // 访问标记  
int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量  

struct State // BFS 队列中的状态数据结构  
{  
    int x,y; // 坐标位置  
    int Step_Counter; // 搜索步数统计器  
};  

State a[maxn];  

boolCheckState(State s) // 约束条件检验  
{  
    if(!vst[s.x][s.y] && ...) // 满足条件         
        return 1;  
    else // 约束条件冲突  
    return 0;  
}  

void bfs(State st)  
{  
    queue <State> q; // BFS 队列  
    State now,next; // 定义2 个状态,当前和下一个  
    st.Step_Counter=0; // 计数器清零  
    q.push(st); // 入队     
    vst[st.x][st.y]=1; // 访问标记  
    while(!q.empty())  
    {  
        now=q.front(); // 取队首元素进行扩展  
        if(now==G) // 出现目标态,此时为Step_Counter 的最小值,可以退出即可  
        {  
            ...... // 做相关处理  
            return;  
        }  
    for(int i=0;i<4;i++)  
    {  
        next.x=now.x+dir[i][0]; // 按照规则生成   下一个状态  
        next.y=now.y+dir[i][1];  
        next.Step_Counter=now.Step_Counter+1; // 计数器加1  
        if(CheckState(next)) // 如果状态满足约束条件则入队  
        {  
            q.push(next);  
            vst[next.x][next.y]=1; //访问标记  
        }  
    }  
    q.pop(); // 队首元素出队  
    }  
 return;  
}  

int main()  
{  
......  
 return 0;  
} 

然后是dfs

#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
using namespace std;  
const int maxn=100;  
bool vst[maxn][maxn]; // 访问标记  
int map[maxn][maxn]; // 坐标范围  
int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量,(x,y)周围的四个方向  

bool CheckEdge(int x,int y) // 边界条件和约束条件的判断  
{  
    if(!vst[x][y] && ...) // 满足条件  
        return 1;  
    else // 与约束条件冲突  
        return 0;  
}  

void dfs(int x,int y)  
{  
    vst[x][y]=1; // 标记该节点被访问过  
    if(map[x][y]==G) // 出现目标态G  
        {  
        ...... // 做相应处理  
        return;  
        }  
    for(int i=0;i<4;i++)  
    {  
        if(CheckEdge(x+dir[i][0],y+dir[i][1])) // 按照规则生成下一个节点  
            dfs(x+dir[i][0],y+dir[i][1]);  
    }  
    return; // 没有下层搜索节点,回溯  
}  
int main()  
{  
......  
return 0;  
}  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DFS算法是一种用于图遍历或树遍历的算法。其核心思想是从起点开始递归地深入每一个可能的分支,直到无法继续为止,然后回溯到上一个节点,继续尝试其他分支。 DFS算法有两种实现方式:递归实现和非递归实现(使用栈)。 递归实现的DFS算法伪代码: ``` DFS(node): if node is None: return visit(node) for child in node.children: DFS(child) ``` 非递归实现的DFS算法伪代码: ``` DFS(node): stack = [node] while stack: node = stack.pop() if node.visited: continue visit(node) node.visited = True for child in node.children: stack.append(child) ``` 其中,visit(node)表示对节点node进行操作,例如打印节点值、记录路径等。 DFS算法的时间复杂度为O(V+E),其中V为节点数,E为边数。因为每个节点和每条边都只会被访问一次。 下面是一个例题,用DFS算法求解从起点到终点的路径(leetcode 79题): 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 示例: ``` board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true. 给定 word = "SEE", 返回 true. 给定 word = "ABCB", 返回 false. ``` 实现代码: ```python class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not board or not board[0]: return False m, n = len(board), len(board[0]) visited = [[False] * n for _ in range(m)] directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def dfs(i, j, k): if k == len(word): return True if i < 0 or i >= m or j < 0 or j >= n or visited[i][j] or board[i][j] != word[k]: return False visited[i][j] = True for dx, dy in directions: if dfs(i+dx, j+dy, k+1): return True visited[i][j] = False return False for i in range(m): for j in range(n): if dfs(i, j, 0): return True return False ``` 时间复杂度为O(m*n*3^k),其中m、n为网格大小,k为单词长度。因为每个格子都有可能走,所以是O(m*n),而每次调用dfs函数会向四个方向递归,每个方向都不能重复走,所以是3^k。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值