【算法】DFS入门

32 篇文章 0 订阅

找子集

    List<Integer> temp = new ArrayList<>();     //子集
    List<List<Integer>> arr = new ArrayList<>();    //存放子集
​
    public void dfs(Integer[] num, int n){
        //讲子集temp添加进arr中
        arr.add(new ArrayList<>(temp));
        for(int i = n;i< num.length;i++){
            temp.add(num[i]);
            dfs(num,i+1);
            temp.remove(temp.size()-1);
        }
    }
    public List<List<Integer>> tar(Integer [] num){
        dfs(num,0);
        return arr;
    }
​
Integer num[] = {1,2,3};
System.out.println(Arrays.toString(tar(num).toArray()));

[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

最短路

int row=10,column=11;
int px=6,py=4,min = 2147483646;
int book[][] = new int[row][column];
public final int[][] next={{1,0},{0,1},{0,-1},{-1,0}};
private int map[][] = new int[][]{
    {0,0,0,0,0,0,1,1,0,0,0},
    {1,0,0,0,0,0,0,0,1,0,1},
    {0,0,0,0,1,1,0,0,1,0,1},
    {1,0,0,0,1,0,1,0,1,0,0},
    {0,0,0,1,0,0,1,0,0,0,0},
    {0,1,1,1,0,0,0,0,1,0,1},
    {0,0,0,1,0,0,1,0,1,0,1},
    {1,0,1,0,1,1,0,0,1,1,1},
    {1,1,0,0,0,0,0,0,0,0,0},
    {1,0,0,1,1,1,0,0,0,0,1}
};
public void dfs(int x,int y,int n){
    int mx,my;
    if (x == px && y == py){
        if (n < min){
            System.out.println("yes\t"+n);
            for (int i =0; i<row;i++){
                for (int j=0;j<column;j++){
                    System.out.print(book[i][j]+" ");
                }
                System.out.println();
            }
            min = n;
        }
        return;
    }
​
    for(int i = 0;i<4;i++){
        mx = x + next[i][0];
        my = y + next[i][1];
​
        if ((mx<0 || mx >=row || my<0 || my >=column) || map[mx][my]==1){
            continue;
        }
        if (book[mx][my]==0){
            book[mx][my] = 1;
            dfs(mx,my,n+1);
            book[mx][my] = 0;
​
        }
    }
    return;
}

二叉树最大深度



    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    int max =-1;
    int flag = 1;
    public int maxDepth(TreeNode root) {
        dfs(root,0);

        return max;
    }
     
    public void dfs(TreeNode root,int n){
        if (root == null){
            max = 0;
            return;
        }else if (flag ==1){
            n++;
            flag=0;
        }
        if (root.right == null && root.left ==null){
            if (n>max){
                max = n;
                //System.out.println("yes\t" + max);
            }
            return;
        }
        if (root.left != null) {
            dfs(root.left, n+1);

        }
        if (root.right != null){
            dfs(root.right, n+1);
        }
        return;

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值