leetcode part8 搜索

本文详细介绍了深度优先搜索和宽度优先搜索两种算法,重点讲解了它们在解决LeetCode 200题——岛屿数量问题中的应用。通过具体代码示例,展示了如何使用这两种搜索策略来计算由'1'和'0'组成的二维网格中岛屿的数量。

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

深度优先搜索使用的数据结构是栈或者使用系统栈(递归函数)
宽度优先搜索使用的数据结构是队列

#include<iostream>
#include<vector>

/**
深度优先搜索和宽度优先搜索

leetcode  200 岛屿数量
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,
计算岛屿的数量。
一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。
你可以假设网格的四个边均被水包围。

**/


using namespace std;

class Solution {
public:
    void dfs(vector<vector<char> >& grid,int i,int j){
        if(i>=0 and i<grid.size() and j>=0 and j<grid[0].size() and grid[i][j]=='1'){
            grid[i][j]='0';

            this->dfs(grid,i-1,j);
            this->dfs(grid,i,j-1);
            this->dfs(grid,i,j+1);
            this->dfs(grid,i+1,j);
        }
        return;
    }
    int numIslands(vector<vector<char> >& grid) {
        int num=0;
        for(int i=0;i<grid.size();i++){
            for(int j=0;j<grid[0].size();j++){
                if(grid[i][j]=='1'){
                    num++;
                    this->dfs(grid,i,j);
                }
            }
        }
        return num;
    }
};


int main(){
    

    return 0;
}

 

### 获取 LeetCode 上热门的 200 题目 LeetCode 是一个广受欢迎的在线编程练习平台,提供了大量的算法挑战和面试准备资源[^2]。为了帮助用户更好地准备技术面试并提升编程技能,LeetCode 维护了一个特别精选的问题列表,称为 "Top Interview Questions" 或者 “Popular Problems”,这些问题是基于社区反馈和技术公司实际面试情况精心挑选出来的。 #### 如何访问 Top 200 Popular Problems 1. 访问 [LeetCode 官方网站](https://leetcode.com/) 2. 导航到页面底部,在“Resources”部分找到并点击“Top Interview Questions” 3. 这里会展示一系列按照难度分类(简单、中等、困难)的经典问题集合 4. 虽然官方并没有明确指出具体数量为200题,但是这个列表包含了最常被提及以及被认为最重要的题目 对于希望深入理解数据结构与算法的人来说,解决这些问题是非常有益处的。通过实践这些经典案例,可以有效提高解决问题的能力,并且熟悉各种常见的解法模式,比如深度优先搜索(DFS)[^3]。 ```python import requests from bs4 import BeautifulSoup def get_top_200_problems(): url = 'https://leetcode.com/problemset/top-interview-questions/' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') problem_list = [] # Assuming there's a specific class or tag structure for listing problems. # This part may need adjustment based on actual HTML structure. items = soup.find_all('div', {'class': 'css-vns2i0'}) count = 0 for item in items: title = item.a.string.strip() link = f"https://leetcode.com{item.a['href']}" difficulty = item.span.string problem_info = { 'title': title, 'link': link, 'difficulty': difficulty } problem_list.append(problem_info) if (count := count + 1) >= 200: break return problem_list[:200] # Note: The above code snippet assumes certain HTML structures which might change over time. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值