力扣-图论-2【算法学习day.52】

前言

###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!


习题

1.所有可能的路径

题目链接: 797. 所有可能的路径 - 力扣(LeetCode)

题面:

分析:简单的dfs

代码:

java 复制代码
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    int n;
    int[][] graph;
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<Integer> list  = new ArrayList<>();
        n = graph.length;
        this.graph = graph;
        int[] flag = new int[n];
        list.add(0);
        recursion(list,0,flag);
        return ans;
    }
    public void recursion(List<Integer> list,int x,int[] flag){
        //  System.out.println(x);
        if(x==(n-1)){
            // System.out.println(1);
            ans.add(new ArrayList<>(list));
        }
        int[] arr = graph[x];
        int m = arr.length;
        for(int i = 0;i<m;i++){
            if(flag[arr[i]]==0){
                list.add(arr[i]);
                flag[arr[i]] = 1;
                recursion(list,arr[i],flag);
                flag[arr[i]] = 0;
                list.remove(list.size()-1);
            }
        } 
    }
}

2.钥匙和房间

题目链接: 841. 钥匙和房间 - 力扣(LeetCode)

题面:

代码:

java 复制代码
class Solution {
    int n;
    int[] have;
    int count;
    int[] flag;
    List<List<Integer>> rooms;
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        this.rooms = rooms;
         n = rooms.size();
         List<Integer> list = rooms.get(0);
         have = new int[n];
         flag = new int[n];
         flag[0] = 1;
         count = n-1;
         have[0] = 1;
         for(int a:list){
            if(have[a]==0)count--;
            have[a] = 1;
         }
         recursion(have);
         System.out.println(count);
         return count==0?true:false;
    }
    public void recursion(int[] have){
        int blog = 0;
        for(int i = 0;i<n;i++){
            if(have[i]==1&&flag[i]==0){
                flag[i] = 1;
                 List<Integer> list = rooms.get(i);
                 for(int a:list){
                    if(have[a]==0)count--;
                     have[a] = 1;
                    
                 }
                 blog = 1;
            }
        }
        if(blog==1)recursion(have);
    }
}

后言

上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!

相关推荐
txxzjmzlh9 分钟前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj5202 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河662 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
老师我太想进步了20263 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志783243 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
SL_staff3 小时前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
特立独行的猫A3 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
UIU1143 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊4 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊5 小时前
LeetCode2001~2020题目解析
java·leetcode