dfs基本思想

dfs基本思想

一.背景

本人在学习了acwing的算法基础课后,对dfs算法有了一定的理解,于是写下了下面的博客。

二.dfs基本介绍

DFS(Depth First Searching)是一种基于递归的算法,其中文名为深度优先搜索算法,那么我们先来通过一个简单的深搜过程了解一下DFS算法的工作原理。
在这里插入图片描述

上图就是dfs在遍历过程的顺序,总结下来就是dfs在遍历过程中会选择一条路走到黑,走完一条路后,回溯一小格,看看另外的分支有每有路可以走。

三.例题

排列数字原题链接

在这里插入图片描述
代码如:

import java.util.*;

public class Main{
    private static int N = 10;
    private static int n;
    private static int[] path = new int[N];
    private static boolean[] st = new boolean[N];
    public static void dfs(int u){
        if(u == n){
            for(int i = 0 ; i < n ; i++){
                System.out.print(path[i]+" ");
            }
            System.out.println();
            return;
        }
        for(int i = 1 ;i <= n ; i++){
            if(!st[i]){
                path[u] = i;
                st[i] = true;
                dfs(u+1);
                path[u] = 0;//恢复现场
                st[i] = false;//恢复现场
            }
        }
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        dfs(0);
        sc.close();
    }
}

n皇后问题
在这里插入图片描述
在这里插入图片描述
代码如下:

import java.util.*;

public class Main{
    public static int N = 20;
    public static int n;
    public static char[][] arr = new char[N][N];
    public static boolean[] dg = new boolean[N];//判断主对角线位置能否放
    public static boolean[] udg = new boolean[N];//判断负对角线能否放
    public static boolean[] col = new boolean[N];
    public static void dfs(int u){
        if(u == n){
            for(int i = 0 ; i < n ; i++){
                for(int j = 0 ; j < n ; j++){
                    System.out.print(arr[i][j]);
                }
                System.out.println();
            }
            System.out.println();
            return;
        }
        
        for(int i = 0 ; i < n ;i++){
            if(!col[i] && !dg[u+i] && !udg[n-u+i]){
                arr[u][i] = 'Q';
                col[i] = dg[u+i] = udg[n-u+i] = true;
                dfs(u+1);
                arr[u][i] = '.';
                col[i] = dg[u+i] = udg[n-u+i] = false;
            }
        }
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        for(int i = 0 ; i < n ; i++){
            for(int j = 0 ; j < n ; j++){
                arr[i][j] = '.';
            }
        }
        dfs(0);
        sc.close();
    }
}

四.总结提升

  1. 在学习dfs算法时,可以通过画出上述的树形结构模拟该题dfs的过程
  2. dfs在搜索的时候就是按照字典序进行排序的了
  3. dfs过后记得恢复现场
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值