图的广度优先搜索(BFS)和深度优先搜索(DFS)算法解析,参考博文,点击这里
文章目录
从某个点出发,找到其他所有的点======建议使用宽度优先搜索。
2.最容易遗漏的地方:递归的退出条件:return总是忘记写了
使用深度优先遍历的时候:主要考试时
全排列
或者是
子集
中的哪一个的变种。
133. 克隆图
思路:
第一步: 克隆点。 只需要用广度优先搜索的方法从根节点出发去遍历一遍图,并且同时克隆出每个点A
相应的克隆点A`保存在map里面,所以map里面存储每个点的对应克隆点。
第二步: 克隆边。再用广度优先搜索的方法遍历一遍图,并且这个时候由于知道一个点A的相邻点点B,
而map里面存储了A的克隆点A`,B的克隆点B`, 所以这个时候也知道A`和B`是相邻点,建立克隆边。
public class Solution {
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
Queue<Node> queue = new LinkedList<>();
HashMap<Node, Node> map = new HashMap<Node, Node>(); //存储一个映射关系
// clone nodes
queue.offer(node);
map.put(node, new Node(node.val)); //开始节点所对应的克隆点,先把他加入到映射关系中
while (!queue.isEmpty()) {
Node head = queue.poll();
for (Node temp : head.neighbors) {
if (!map.containsKey(temp)) {
map.put(temp, new Node(temp.val));
queue.offer(temp);
}
map.get(head).neighbors.add(map.get(temp));
}
}
return map.get(node);
}
}
拓扑排序
思路: 宽度优先搜索有一个条件就是每一次只能遍历当前入度为0的点,也就是说宽度优先所有的队列中只能放入入度为0的点,然后每次遍历一个点之后,就更新这个点相邻的点的入度信息,因为遍历了这个点,相当于相邻的点的依赖前序工序减少了1个,也就是相邻点的入度减少了1,如果相邻点中更新后有入度为0的点,那么我们就把相邻点放入到队列当中以便下一次进行访问。
通过这样的方法我们遍历一遍整个图。用O(m),m为图的边数,的时间复杂度就可以求出这个图的拓扑排序解。
其实思路都是弹出结点,然后操作的是他的neighbor结点。
补充:队列中
1.尽量使用offer()方法添加元素,使用poll()方法移除元素。dd()和remove()方法在失败的时候会抛出异常。
2.peek方法不会删除元素, Retrieves, but does not remove, the head of this queue,
public class Solution {
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
// write your code here
ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>(); //返回的结果
HashMap<DirectedGraphNode, Integer> map = new HashMap(); //点和入度之间的对应关系。
for (DirectedGraphNode node : graph) { //首先遍历途中的结点,记录入度
for (DirectedGraphNode neighbor : node.neighbors) {
if (map.containsKey(neighbor)) {
map.put(neighbor, map.get(neighbor) + 1); //如果之前有,在之前的基础上在加一个入度
} else {
map.put(neighbor, 1); //之前没有,则设置当前结点的入度为1
}
}
}
Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
for (DirectedGraphNode node : graph) { //遍历结点,将入度为0 的结点加入到队列之中去。
if (!map.containsKey(node)) {
q.offer(node);
result.add(node);
}
}
while (!q.isEmpty()) {
DirectedGraphNode node = q.poll();
for (DirectedGraphNode n : node.neighbors) {
map.put(n, map.get(n) - 1); //当前结点的入度减一
if (map.get(n) == 0) {
result.add(n);
q.offer(n);
}
}
}
return result;
}
}
46.全排列
思路:这种求解所有的可能解的问题,首先考虑使用深度优先搜索
易错:
1.辅助函数不需要返回值的,因为传入的参数是引用类型的,传入的直接是地址,在内部函数中改变值,外面也会因此改变的
2.在辅助函数的循环中的判断,容易忽略
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if(nums == null || nums.length == 0){
return result;
}
permuteHelper(result,list,nums);
return result;
}
public void permuteHelper(List<List<Integer>> result, List<Integer> list,int[] nums){
if(list.size() == nums.length){
result.add(new ArrayList<Integer>(list));
return ;
}
for(int num:nums){
if(!list.contains(num)){ //因为给定是没有重复的序列,所以直接这样使用
list.add(num);
permuteHelper(result,list,nums);
list.remove(list.size()-1);
}
}
}
}
下面这种使用数组进行优化,将查询时间复杂度由O(n)--------》O(1);
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
boolean[] used = new boolean[nums.length];
if(nums == null || nums.length == 0){
return result;
}
permuteHelper(result,list,used,nums);
return result;
}
public void permuteHelper(List<List<Integer>> result,
List<Integer> list,
boolean[] used,
int[] nums){
if(list.size() == nums.length){
result.add(new ArrayList<Integer>(list));
return ;
}
for(int i=0;i<nums.length;i++){ //表示横向的处理逻辑。
if(used[i]){
continue;
}
used[i] =true; //表示在递归过程中已使用。
list.add(nums[i]);
permuteHelper(result,list,used,nums);
used[i] =false; //每次递归完成之后,将还原程没有使用,
list.remove(list.size()-1);
}
}
}
47. 全排列 II
LeetCode上有详解,主要是对于剪枝条件的选定。
注意: Arrays.sort(nums); 他的主要目的是为了结合nums[i] == nums[i-1] 。来判定去重条件的。
易错:
1.容易忘掉:Arrays.sort(nums);
2.两个used[i]的位置和顺序;
3.if(used[i]):的判断也容易忘记
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
boolean[] used = new boolean[nums.length];
if(nums == null || nums.length == 0){
return result;
}
Arrays.sort(nums);
permuteHelper(result,list,used,nums);
return result;
}
public void permuteHelper(List<List<Integer>> result,
List<Integer> list,
boolean[] used,
int[] nums){
if(list.size() == nums.length){
result.add(new ArrayList<Integer>(list));
return ;
}
for(int i=0;i<nums.length;i++){
if(used[i]){ //每次找的时候都需要找本次深度优先搜索中没有使用过的数。
continue;
}
if(i>0 && nums[i] == nums[i-1] && !used[i-1]){
continue ;
}
used[i] =true;
list.add(nums[i]);
permuteHelper(result,list,used,nums);
used[i] =false;
list.remove(list.size()-1);
}
}
}
78.子集
思路:
1.这道题和46题的区别是选取一个数之后,前面的数就不能当做备选了,这种是避免出现重复的子集
2.这道题添加结果集是每一个中间过程所得的值都需要加入的。(每一层都是可行解)
易错:
1.递归的时候的+1操作是对i的,而不是对j的
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<Integer>();
dfs(result,temp,nums,0);
return result;
}
public void dfs(List<List<Integer>> result,List<Integer> temp,int[] nums,int j){
result.add(new ArrayList<Integer>(temp)); //如果直接使用temp值传入的话,传入的是一个地址,那么在后面回溯的时候值会发生改变,则不满足题最初的意思。
for(int i = j; i < nums.length; i++){
temp.add(nums[i]);
dfs(result,temp,nums,i+1);
temp.remove(temp.size()-1);
}
}
}
51.N-皇后问题
题目:就是皇后不能在同一行,同一列,同一个斜线上
下面是左对角线的性质:x+y等于同一个值。
下面是右对角线的性质:x-y等于同一个值。
class Solution {
List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
if (n <= 0) {
return results;
}
search(results, new ArrayList<Integer>(), n);
return results;
}
/*
* results store all of the chessboards
* cols store the column indices for each row
* cols:存储每一行的列的索引
*/
private void search(List<List<String>> results,
List<Integer> cols,
int n) {
if (cols.size() == n) {
results.add(drawChessboard(cols));
return;
}
for (int colIndex = 0; colIndex < n; colIndex++) {
if (!isValid(cols, colIndex)) { //剪枝条件,如果不满足,则直接跳过
continue;
}
cols.add(colIndex);
search(results, cols, n);
cols.remove(cols.size() - 1);
}
}
private List<String> drawChessboard(List<Integer> cols) { //有皇后的排列组合,得出最后的输出结果。
List<String> chessboard = new ArrayList<>();
for (int i = 0; i < cols.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < cols.size(); j++) {
sb.append(j == cols.get(i) ? 'Q' : '.');
}
chessboard.add(sb.toString());
}
return chessboard;
}
private boolean isValid(List<Integer> cols, int column) { //cols:索引:行数,值:列数
int row = cols.size(); //这个放置之前,一共有多少行,也是多少个皇后
for (int rowIndex = 0; rowIndex < cols.size(); rowIndex++) { //每一行的皇后都要与将要放置的皇后判定是否在同一行,同一列,同一斜线
if (cols.get(rowIndex) == column) { //判定是否在同一列
return false;
}
if (rowIndex + cols.get(rowIndex) == row + column) { //判定是否在左对角线上
return false;
}
if (rowIndex - cols.get(rowIndex) == row - column) { //判定是否在有对角线上。
return false;
}
}
return true;
}
}
90.子集II
注意:去重的条件:
注意:这里的剪枝条件其实是:作用在递归树的同一层上的,也就是横向去观察的那种
class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
// write your code here
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null) return results;
if (nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
List<Integer> subset = new ArrayList<Integer>();
helper(nums, 0, subset, results);
return results;
}
public void helper(int[] nums, int startIndex, List<Integer> subset, List<List<Integer>> results){
results.add(new ArrayList<Integer>(subset));
for(int i=startIndex; i<nums.length; i++){
if (i != startIndex && nums[i]==nums[i-1]) {// 去重,如果有重复数字出现,只有前上一个数字选了才能选当前数字
continue;
}
subset.add(nums[i]);
helper(nums, i+1, subset, results);
subset.remove(subset.size()-1);
}
}
}
131.分割回文串。
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<List<String>>();
if(s == null || s.length() == 0){
return result;
}
List<String> list = new ArrayList<String>();
partitionHelper(result,list,0,s);
return result;
}
public void partitionHelper(List<List<String>> result,List<String> list,int startIndex,String s){
if(startIndex == s.length()){
result.add(new ArrayList<String>(list));
return ;
}
for(int i = startIndex;i < s.length();i++){
String subString = s.substring(startIndex, i + 1); //每一次递归的处理逻辑,进行插入取值。
if(!isPalidrome(subString)){
continue;
}
list.add(subString);
partitionHelper(result,list,i+1,s);
list.remove(list.size()-1);
}
}
public boolean isPalidrome(String s){
for(int i=0,j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)){
return false;
}
}
return true;
}
}
39.组合总和
注意:最容易遗漏的地方:
1.Arrays.sort();
2.result.add(new ArrayList(list));
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(candidates ==null || candidates.length == 0){
return result;
}
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(candidates);
combinationSumHelper(candidates,target,0,result,list);
return result;
}
public void combinationSumHelper(int[] candidates,int target,int startIndex,List<List<Integer>> result,List<Integer> list){
if(target == 0){
result.add(new ArrayList<Integer>(list));
return;
}
for(int i =startIndex;i<candidates.length;i++){
if(target<candidates[i]){
break;
}
list.add(candidates[i]);
//【关键】因为元素可以重复使用,这里递归传递下去的是 i 而不是 i + 1
combinationSumHelper(candidates,target-candidates[i],i,result,list);
list.remove(list.size()-1);
}
}
}
容易错的两种写法:
具体来说,combinationSumHelp1函数在每次递归时都会更新target的值,而combinationSumHelp2函数则在递归时直接使用target - candidates[i]。这导致在combinationSumHelp1函数中,每次递归都会更新target的值,因此在递归回溯时,target的值会被还原到之前的状态。而在combinationSumHelp2函数中,递归时直接使用target - candidates[i],因此在递归回溯时,target的值不会被还原到之前的状态。
public void combinationSumHelp1(int[] candidates,List<List<Integer>> result,List<Integer> list, int target,int j){
if(target == 0){
result.add(new ArrayList<Integer>(list));
return;
}
for(int i= j ;i < candidates.length;i++){
if(target < candidates[i]){
break;
}
list.add(candidates[i]);
target = target - candidates[i];
combinationSumHelp1(candidates,result,list, target,i);
list.remove(list.size()-1);
}
}
public void combinationSumHelp2(int[] candidates,List<List<Integer>> result,List<Integer> list, int target,int j){
if(target == 0){
result.add(new ArrayList<Integer>(list));
return;
}
for(int i= j ;i < candidates.length;i++){
if(target < candidates[i]){
break;
}
list.add(candidates[i]);
combinationSumHelp2(candidates,result,list, target - candidates[i],i);
list.remove(list.size()-1);
}
}
public List<List<Integer>> combinationSum1(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if(candidates ==null || candidates.length == 0){
return result;
}
Arrays.sort(candidates);
combinationSumHelp1(candidates,result,list,target,0);
return result;
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if(candidates ==null || candidates.length == 0){
return result;
}
Arrays.sort(candidates);
combinationSumHelp2(candidates,result,list,target,0);
return result;
}
40.数字组合 II
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
if(candidates == null || candidates.length==0){
return result;
}
Arrays.sort(candidates);
combinationSum2Helper(candidates,target,0,result,list);
return result;
}
public void combinationSum2Helper(int[] candidates,int target,int startIndex,List<List<Integer>> result,List<Integer> list){
if(target == 0){
result.add(new ArrayList<Integer>(list));
}
for(int i =startIndex;i<candidates.length;i++){
if(i!=startIndex&&candidates[i] == candidates[i-1]){
continue;
}
if(target<candidates[i]){
break;
}
list.add(candidates[i]);
combinationSum2Helper(candidates,target-candidates[i],i+1,result,list );
list.remove(list.size()-1);
}
}
}
113.路径总和 II
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
helper(result,new ArrayList<Integer>(),sum,root);
return result;
}
private void helper(List<List<Integer>> result,List<Integer> list,int target,TreeNode root){
if(root == null){
return;
}
if( root.left == null && root.right == null && root.val ==target){
list.add(root.val);
result.add(new ArrayList<Integer>(list));
list.remove(list.size()-1);
return;
}
list.add(root.val);
helper(result,list,target - root.val,root.left);
helper(result,list,target - root.val,root.right);
list.remove(list.size()-1);
}
}
剑指offer 12. 矩阵中的路径
标记当前矩阵元素: 将 board[i][j] 值暂存于变量 tmp ,并修改为字符 ‘/’ ,代表此元素已访问过,防止之后搜索时重复访问。
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
for(int i = 0;i < board.length;i++){
for(int j = 0;j < board[0].length;j++){
if(solve(board,words, i, j,0)){
return true;
}
}
}
return false;
}
private boolean solve(char[][] board,char[] words,int i,int j,int index){
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != words[index]){
return false;
}
if(index == words.length-1){
return true;
}
char temp = board[i][j];
board[i][j] = '/';
boolean res = solve(board,words,i+1,j,index+1) ||
solve(board,words,i,j+1,index+1) ||
solve(board,words,i-1,j,index+1) ||
solve(board,words,i,j-1,index+1);
board[i][j] = temp;
return res;
}
}
机器人的运动范围
class Solution {
public int movingCount(int m, int n, int k) {
// 方向数组:x,y上下对应,代表4个方向
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0,0});
boolean[][] visited = new boolean[m][n];
visited[0][0] = true;
while(!queue.isEmpty()){
int[] cur = queue.poll();
for(int i = 0;i < 4;i++){
int x = cur[0] + dx[i];
int y = cur[1] + dy[i];
if(x < 0 || x >= m || y >= n || y < 0 ){
continue;
}
int value = solve(x) + solve(y);
if(value > k || visited[x][y]){
continue;
}
visited[x][y] =true;
queue.offer(new int[]{x,y});
}
}
int res = 0;
for(int i = 0;i <m;i++){
for(int j =0;j<n;j++){
if(visited[i][j]){
res++;
}
}
}
return res;
}
private int solve(int num){
int sum = 0;
while(num > 0){
int temp = num % 10;
num /= 10;
sum += temp;
}
return sum;
}
}