LeetCode5. 深度优先搜索,回溯,广度优先搜索

深度优先搜索(Depth-first Search, DFS),广度优先搜索(breadth-first Search, BFS)

一、简介和对比思考

1、怎么理解DFS和BFS的区别?

DFS: 是按深度遍历的,在搜索到一个节点时,立即对该节点遍历其左右子节点。因此需要用先入后出的栈来实现。也可以通过与栈等价的递归来实现。

BFS:是按层遍历的,因此需要用先入先出的队列来实现。由于BFS的按层遍历,它常被用来处理最短路径问题。

2、怎么理解DFS和BFS的区别?(通过题目去加强理解,这些都是我可以自己写出来的,相信自己)

DFS:理解如何通过栈或者递归,实现二叉树中和为某固定值的路径的搜索(力扣

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {

private:
  vector<vector<int>> res; //返回结果List
  vector<int> path; //记录当前路径

public:
  vector<vector<int>> pathSum(TreeNode* root, int target) {
    dfs(root, target);
    return res;
  }
  
  void dfs(TreeNode* curr, int target) {
    //1. 判断退出条件
    if (not curr) return;

    //2. 修改当前状态
    path.push_back(curr->val);

    //3. 递归左右子节点
    if (target - curr->val != 0 || curr->left || curr->right) {
      dfs(curr->left, target - curr->val);
      dfs(curr->right, target - curr->val);
    }
    else res.push_back(path);

    //4. 回溯
    path.pop_back(); //删除当前节点
  }
};

BFS:理解如何通过队列实现按层遍历(力扣

class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        if (not root) return {};
        queue<TreeNode*> queue; //注意C++中队列的定义和使用方法
        queue.push(root);
        vector<int> res;
        while(not queue.empty()) {
            //a. 队列第一个元素出队;
            TreeNode* first = queue.front();
            res.push_back(first->val);
            queue.pop();
            //b. 将出队元素的左右子节点入队;
            if (first->left) queue.push(first->left);
            if(first->right) queue.push(first->right);
        }
        return res;
    }
};

一、深度优先搜索

1、求最大岛屿面积  Leetcode695

思路:首先对于这样一个二维数组,我应该怎么去遍历它?第一步是要找到什么?

按照从上到下,从左到右的顺序依次遍历,要找到第一个值为1的位置,然后从这个位置开始,进行深度优先搜索。

class Solution {
public:
  int maxAreaOfIsland(vector<vector<int>>& grid) {
    int m = grid.size();
    int n = grid[0].size();
    int area, max_area = 0;
    vector<vector<bool>> havesearched(m, vector<bool>(n, false));
    for (int i = 0; i < m; i++) {
      for(int j = 0; j < n; j++) {
        if (grid[i][j] == 1 && (not havesearched[i][j])) {
          area = 0;
          dfs(grid, havesearched, i, j, m, n, area);
          max_area = max(area, max_area);
        }
      }
    }
    return max_area;
  }

  void dfs()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值