0
点赞
收藏
分享

微信扫一扫

【回溯算法】数据结构与算法

雅典娜的棒槌 2022-02-12 阅读 70

        回溯算法实际上是一个类似穷举的的搜索尝试过程,主要是在搜索尝试过程中寻找问题的阶,当发现已不满足求解条件时就“回溯”(即回退),尝试其他路径,所以回溯法有“通常的解题法”之称。

        从一条路往前走,能进则进,不能进则退回来,换一条路再试试。

回溯算法的应用:

问题一:全排列问题:

        求解字符串“ABC”中所有字符的全排列问题(不包含重复)

        ABC ACB BAC CAB CBA

        而对于字符串“ABB”而言的所有全排列

        ABB BAB BBA

        问题分析:

如图:首先字符串是不可变的,我们可以将字符串格式化成为数组。f表示数组第一个元素的下标,t表示数组最后一个元素的下标。我们让f位置上的字符与首位置上的字符进行交换,之后再让f向后移一个位置,然后我们接着将f + 1位置到t位置上的字符在紧接着上面的操作。停止递归的条件就是f==t的时候

代码如下:

import java.util.HashSet;

public class FullPermutation {
    public static void main(String[] args) {
        String s = "ABC";
        char[] arr = s.toCharArray();           //将字符串格式化成数组。方便进行修改
        HashSet<String> set = new HashSet<>();      //去重(Hashset自带去重效果)

        //定义一个实现功能的方法
        /*
        将正确的排序储存进set里面,Hashset是会自动筛选出重复元素的
        对字符数组进行操作,筛选出符合条件的字符
        对字符进行筛选的范围
         */
        Permutation(set, arr, 0, arr.length - 1);
        System.out.println(set);
    }

    private static void Permutation(HashSet<String> set, char[] arr, int from, int to) {
        if(from == to){
            set.add(String.valueOf(arr));       //将字符数组格式化为字符串  [A,B,C] => "ABC"
        }else {
            for (int i = from; i <= to; i++) {
                swap(arr, i, from);
                Permutation(set, arr, from + 1, to) ;
                //注意每一次交换过后都要交换回去
                swap(arr, i, from);
            }
        }
    }

    private static void swap(char[] arr, int i, int j) {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

运行结果:

 


问题二:迷宫问题

         我们想要从(1,0)到(7,8),我们可以将起点坐标设为(1,0),然后令“1”为墙,“0”为路,之后我们让当前点坐标由“上右下左”的的顺序遍历寻找路,当遇到死胡同的时候就回退(我们可以创建一个栈来储存路线,当回退的时候就弹栈,找到路的时候就进栈),回退的时候注意我们应该在回退的那个位置做一个标记,防止死循环(我们可以创建一个Boolean类型的二维数组,在回退的那个位置标记true)。最后我们输出栈,如果找到了路就输出站的内容,否则就输出“迷宫不通”。

代码如下:

import java.util.LinkedList;

public class Maze {
    private static int[][] maze = {
            {1, 1, 1, 1, 1, 1, 1, 1, 1},
            {0, 0, 1, 0, 0, 0, 1, 1, 1},
            {1, 0, 1, 1, 1, 0, 1, 1, 1},
            {1, 0, 0, 1, 0, 0, 1, 1, 1},
            {1, 1, 0, 1, 1, 0, 0, 0, 1},
            {1, 0, 0, 0, 0, 0, 1, 0, 1},
            {1, 0, 1, 1, 1, 0, 0, 0, 1},
            {1, 1, 0, 0, 0, 0, 1, 0, 0},
            {1, 1, 1, 1, 1, 1, 1, 1, 1}
    };
    //入口信息
    private static int entryX = 1;
    private static int entryY = 0;

    //出口信息;
    private static int exitX = 7;
    private static int exitY = 8;

    //路径访问状态表
    private static boolean[][] vistied = new boolean[9][9];

    //方向的变化量
    private static int[][] direction = {{1,0}, {0, 1}, {0, -1}, {-1, 0}};

    //储存路径的栈
    private static LinkedList<String> stack = new LinkedList<>();

    public static void main(String[] args) {
        boolean flag = go(entryX, entryY);
        if (flag){
            for (String path: stack){
                System.out.println(path);
            }
        }else {
            System.out.println("迷宫不通!");
        }
    }

    private static boolean go(int entryX, int entryY) {
        stack.push("(" + entryX + ", " + entryY + ")");
        vistied[entryX][entryY] = true;
        if (entryX == exitX && entryY == exitY){
            return true;
        }
        //考虑四个方向    上、右、下、左
        for (int i = 0; i < direction.length; i++) {
            int newX = direction[i][0] + entryX;
            int newY = direction[i][1] + entryY;
            if (isLnArea(newX, newY) && isRoad(newX, newY) && !vistied[newX][newY]){
                if (go(newX,newY)){
                    return true;    //  某一个方向能通过则向上返回true 表示此层次x y能通过
                }
            }
        }
        stack.pop();
        return false;       //如果四个方向都不通,则向上放回false表示此层次x y 不通
    }

    private static boolean isRoad(int newX, int newY) {
        return maze[newX][newY] == 0;
    }

    private static boolean isLnArea(int newX, int newY) {
        return newX >=0 && newX <9 && newY >= 0 && newY < 9;
    }
}

运行结果:
        

问题三: 八皇后问题:
        在一个8X8的棋盘中,放入8个皇后的棋子,要求同行同列同斜线不能有重复的皇后棋子。

         我们以棋盘的第一个位置为起点,然后以列去遍历,在遍历的时候加入判断,判断该位置能不能放棋子,当棋盘的一行放好后就去遍历下一行(row表示行,col表示列),当遍历到某一行的时候发现每一列都不能放棋子后,就回退去上一行,让上一行接着往下遍历。直到当row到达了棋盘外就停止递归。

代码如下:
 

public class NQueen {
    private static int count = 0;//记录解的个数
    private static final int N = 8; //N皇后矩阵的尺寸
    private static int[][] arr = new int[N][N];//棋盘数据0表示空 1表示皇后

    public static void main(String[] args) {
        queen(0);
    }

    //递归的解决row角标行皇后的问题,如果row == N说明一个解就出来了,row是从0开始遍历的
    private static void queen(int row) {
        if (row == N){
            count++;
            System.out.println("第" + count + "个解:");
            printArr();
        }else {
            //遍历当前的列
            for (int col = 0; col < N; col++) {
                //判断该点位置与其他位置的棋子是否有冲突
                if (!isDangerous(row, col)){
                    //每次要放置皇后的时候 都先对改行进行清空
                    for (int c = 0; c < N; c++){
                        arr[row][c] = 0;
                    }
                    arr[row][col] = 1;
                    queen(row + 1);
                }
            }
        }
    }

    private static void printArr() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }

    private static boolean isDangerous(int row, int col) {
        //向上
        for (int r = row - 1; r >= 0; r--) {
            if (arr[r][col] == 1){
                return true;
            }
        }
        //向左上
        for (int r = row - 1, c = col - 1 ; r >=0 && c >= 0; r--, c--) {
            if (arr[r][c] == 1){
                return true;
            }
        }
        //右上
        for (int r = row - 1, c = col + 1; r >= 0 && c < N; r--, c++){
            if (arr[r][c] == 1){
                return true;
            }
        }
        return false;
    }

}

输出结果:

 问题四:数独问题

        每一行、每一列、每一个粗线宫(3X3)内的数字均含有1~9、不重复

         解题思路:与八皇后问题类似,将第一个带点为起点从1~9之间遍历看每一行、每一列、每一个粗线宫(3X3)内的数字是否重复,如果1~9都以重复就向上回退,让上一个格子接着遍历后面的数,如果不重复就填入格子中。当格子中有数字时,就直接跳过

代码如下:

package p4.分治回溯;

import java.io.*;
//数独
public class Sudoku {
    private static int i = 0;
    private static int[][] board = new int[9][9];

    public static void main(String[] args) throws IOException {
        readFile("sudoku_data_01.txt");
        solve(0, 0);
    }

    //求解x-y格子的解 再继续向下递归求解下一个格子
    //本质求多个解 但实际 数独问题只能有一个解 如果没解 程序啥也不输出!
    private static void solve(int row, int col) {
        if (row == 9) {
            i++;
            System.out.println("===========" + i + "==========");
            printBoard();
            //System.exit(0);
        } else {
            if (board[row][col] == 0) {
                //需要填数字1~9
                for (int num = 1; num <= 9; num++) {
                    if (!isExist(row, col, num)) {
                        board[row][col] = num; //8
                        //解决下一个格子
                        solve(row + (col + 1) / 9, (col + 1) % 9);
                    }
                    //如果此处没解 必须清零
                    board[row][col] = 0;
                }
            } else {
                //已经存在一个已知数字 直接跳过去解决下一个格子
                solve(row + (col + 1) / 9, (col + 1) % 9);
            }
        }
    }

    private static boolean isExist(int row, int col, int num) {
        //同行
        for (int c = 0; c < 9; c++) {
            if (board[row][c] == num) {
                return true;
            }
        }

        //同列
        for (int r = 0; r < 9; r++) {
            if (board[r][col] == num) {
                return true;
            }
        }

        //同九宫 3*3
        int rowMin = 0;
        int colMin = 0;

        int rowMax = 0;
        int colMax = 0;

        if (row >= 0 && row <= 2) {
            rowMin = 0;
            rowMax = 2;
        }
        if (row >= 3 && row <= 5) {
            rowMin = 3;
            rowMax = 5;
        }
        if (row >= 6 && row <= 8) {
            rowMin = 6;
            rowMax = 8;
        }
        if (col >= 0 && col <= 2) {
            colMin = 0;
            colMax = 2;
        }
        if (col >= 3 && col <= 5) {
            colMin = 3;
            colMax = 5;
        }
        if (col >= 6 && col <= 8) {
            colMin = 6;
            colMax = 8;
        }

        for (int r = rowMin; r <= rowMax; r++) {
            for (int c = colMin; c <= colMax; c++) {
                if (board[r][c] == num) {
                    return true;
                }
            }
        }

        return false;
    }

    private static void readFile(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
        int row = 0;
        while ((line = br.readLine()) != null) {
            for (int col = 0; col < 9; col++) {
                board[row][col] = Integer.parseInt(line.charAt(col) + "");
            }
            row++;
        }
    }

    private static void printBoard() {
        for (int i = 0 ; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }
}

文本文档内容:

         执行结果:

 

举报

相关推荐

0 条评论