綿陽 網(wǎng)站設(shè)計(jì)推廣引流哪個軟件最好
前言
###我做這類文章一個重要的目的還是給正在學(xué)習(xí)的大家提供方向和記錄學(xué)習(xí)過程(例如想要掌握基礎(chǔ)用法,該刷哪些題?)我的解析也不會做的非常詳細(xì),只會提供思路和一些關(guān)鍵點(diǎn),力扣上的大佬們的題解質(zhì)量是非常非常高滴!!!
習(xí)題
1.所有可能的路徑
題目鏈接:797. 所有可能的路徑 - 力扣(LeetCode)
題面:
分析:簡單的dfs
代碼:
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)
?題面:
代碼:
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);}
}
后言
上面是力扣圖論專題,下一篇是其他的習(xí)題,希望有所幫助,一同進(jìn)步,共勉!