深度优先搜索DFS

120 阅读2分钟

Snipaste_2023-03-08_18-17-45.png

  • 搜索方式:一条路走到底,前面没有路才回头
  • 数据结构:栈stack
  • 空间:O(h)
  • 不具有最短性
  • 在dfs的过程中,最重要的就是两个操作:回溯和剪枝

练习

01 排列数字

  • 题目

Snipaste_2023-03-13_17-40-07.png

  • 题解

Snipaste_2023-03-08_19-31-19.png

import java.io.*;

public class Main {
    public static final int N = 10;
    public static int n;
    public static int[] path = new int[N];
    public static boolean[] st = new boolean[N];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = Integer.parseInt(br.readLine());

        dfs(0);
        pw.close();
        br.close();

    }

    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;//找完就return
        }

        for (int i = 1; i <= n; i++) {
            if (!st[i]) {
                path[u] = i;
                st[i] = true;
                dfs(u + 1);
                //回溯
                path[u] = 0;//这句话可以不写,因为回溯后再次dfs的时候会覆盖
                st[i] = false;
            }
        }
    }
}

02 n-皇后问题

  • 题目

Snipaste_2023-03-13_17-41-44.png

  • 题解
//按行搜
import java.io.*;
import java.util.*;

public class Main {
    public static final int N = 10;
    public static int n;
    public static boolean[] col = new boolean[N];
    public static boolean[] dg = new boolean[2 * N];
    public static boolean[] udg = new boolean[2 * N];
    public static char[][] res = new char[N][N];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            Arrays.fill(res[i], '.');
        }

        dfs(0);
        pw.close();
        br.close();
    }

    public static void dfs(int x) {
        if (x == n) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.print(res[i][j]);
                }
                System.out.println();
            }
            System.out.println();
        }

        for (int y = 0; y < n ; y++) {
            if (!col[y] && !dg[x + y] && !udg[y - x + n]) {
                res[x][y] = 'Q';
                col[y] = dg[x + y] = udg[y - x + n] = true;
                dfs(x + 1);
                //回溯
                res[x][y] = '.';
                col[y] = dg[x + y] = udg[y - x + n] = false;
            }
        }
    }
}
//按格搜
import java.io.*;
import java.util.*;

public class Main {
    public static final int N = 10;
    public static int n;
    public static boolean[] row = new boolean[N];
    public static boolean[] col = new boolean[N];
    public static boolean[] dg = new boolean[2 * N];
    public static boolean[] udg = new boolean[2 * N];
    public static char[][] res = new char[N][N];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            Arrays.fill(res[i], '.');
        }

        dfs(0, 0, 0);
        pw.close();
        br.close();
    }

    public static void dfs(int x, int y, int s) {
        if (y == n) {
            y = 0;
            x++;
        }

        if (x == n) {
            if (s == n) {
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        System.out.print(res[i][j]);
                    }
                    System.out.println();
                }
                System.out.println();
            }
            return;
        }

        if (!row[x] && !col[y] && !dg[x + y] && !udg[y - x + n]) {
            res[x][y] = 'Q';
            row[x] = col[y] = dg[x + y] = udg[y - x + n] = true;
            dfs(x, y + 1, s + 1);
            //回溯
            res[x][y] = '.';
            row[x] = col[y] = dg[x + y] = udg[y - x + n] = false;
        }
        dfs(x, y + 1, s);
    }
}