图论第6天

提高效率!!!两道题+看并查集

841.钥匙和房间

忘了把visited 加引用了:&

cpp 复制代码
class Solution {
public:
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        vector<int>visited(rooms.size(),false);
        dfs(rooms,visited,0);
        for(int i = 0;i < rooms.size();i++){
            if(visited[i] == false)return false;
        }
        return true;
    }
    void dfs(vector<vector<int>>& rooms,vector<int>&visited,int key){
        if(visited[key] == true)return;
        visited[key] = true;
        vector<int>keys = rooms[key];
        for(int i = 0; i < keys.size();i++){
            dfs(rooms,visited,keys[i]);
        }
    }
};

463. 岛屿的周长

第一是不要算重边即可。

第二是有两个挨着的岛屿就总周长减2。

第三这题不用dfs or bfs。

cpp 复制代码
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int island_num = 0;
        int count = 0;
        for(int i = 0;i < grid.size();i++){
            for(int j = 0;j < grid[0].size();j++){
                if(grid[i][j] == 1){
                    island_num++;
                    if((i - 1) >= 0 && grid[i-1][j] == 1)count++;
                    if((j-1) >= 0 && grid[i][j-1] == 1)count++;
                }
            }
        }
        return island_num * 4 - count * 2;
    }
};

图论还剩三道题,明天争取拿下!!!

相关推荐
漂流瓶jz2 小时前
【AI】大模型LoRA微调原理与实验:基于CMRC2018与Qwen3-0.6B训练实测
人工智能·算法·llm
我叫黑大帅6 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
罗西的思考6 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
Navigator_Z8 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
电科_银尘9 小时前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao9 小时前
算法68,字符串相乘
算法
Huangjin007_10 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
驭渊的小故事12 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
htzyl20613 小时前
金额计算:为什么前端不该用浮点数存钱
前端·javascript·算法
电科_银尘13 小时前
【大模型算法与工程 32】全量微调与参数高效微调:如何选择
人工智能·算法·机器学习