回溯法之矩阵中的路径和机器人的运动范围

1. 回溯法

回溯法解决非常适合有多个步骤组成的问题,并且每个步骤都有多个选项。用回溯法解决的问题的所有选项可以形象地用树状结构表示。如果再叶节点的状态不满足约束条件。那么只好回溯它的上一个节点再尝试其他的选项。

1.1 矩阵中的路径
public class Solution1 {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        //标志位,初始化为false
        boolean[] flag = new boolean[matrix.length];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (judge(matrix, i, j, rows, cols, flag, str, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean judge(char[] matrix, int i, int j, int rows, int cols, boolean[] flag, char[] str, int k) {
        //先根据i和j计算匹配的第一个元素转为一维数组的位置
        int index = i * cols + j;
        //递归终止条件
        if (i < 0 || j < 0 || i >= rows || j >= cols || matrix[index] != str[k] || flag[index] == true)
            return false;
        //若k已经到达str末尾了,说明之前的都已经匹配成功了,直接返回true即可
        if (k == str.length - 1)
            return true;
        //要走的第一个位置置为true,表示已经走过了
        flag[index] = true;

        //回溯,递归寻找,每次找到了就给k加一,找不到,还原
        if (judge(matrix, i - 1, j, rows, cols, flag, str, k + 1) ||
                judge(matrix, i + 1, j, rows, cols, flag, str, k + 1) ||
                judge(matrix, i, j - 1, rows, cols, flag, str, k + 1) ||
                judge(matrix, i, j + 1, rows, cols, flag, str, k + 1)) {
            return true;
        }
        //走到这,说明这一条路不通,还原,再试其他的路径
        flag[index] = false;
        return false;
    }

    public static void main(String[] args) {
        char[] matrix = {'a', 'b', 't', 'g', 'c', 'f', 'c', 's', 'j', 'd', 'e', 'h'};
        char[] str = {'b', 'f', 'c', 'e'};
        Solution1 solution1 = new Solution1();
        System.out.println(solution1.hasPath(matrix, 3, 4, str));
    }

}

1.2 机器人的运动范围
public class Solution2 {
    public int movingCount(int threshold, int rows, int cols) {
        if (threshold < 0 || rows <= 0 || cols <= 0) {
            return 0;
        }
        boolean[][] isVisit = new boolean[rows][cols];
        int count = movingCountCore(threshold, rows, cols, 0, 0, isVisit);
        return count;
    }

    private int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[][] isVisit) {
        if (row < 0 || col < 0 || row >= rows || col >= cols || isVisit[row][col] || cal(col) + cal(row) > threshold) {
            return 0;
        }
        isVisit[row][col] = true;
        return 1 + movingCountCore(threshold, rows, cols, row - 1, col, isVisit)
                + movingCountCore(threshold, rows, cols, row + 1, col, isVisit)
                + movingCountCore(threshold, rows, cols, row, col - 1, isVisit)
                + movingCountCore(threshold, rows, cols, row, col + 1, isVisit);
    }

    private int cal(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        System.out.println(solution2.movingCount(-5, 18, 18));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 回溯法求迷宫路径回溯法求解迷宫路径的基本思路是从起点开始,尝试向不同方向走,如果某个方向可以走通,则继续向前探索;如果某个方向走不通,则回溯到上一个位置,尝试其他方向。具体实现可以使用递归算法,代码如下: ```python def find_path(x, y, maze, path): # 判断当前位置是否越界或者是障碍物 if x < 0 or x >= len(maze) or y < 0 or y >= len(maze[0]) or maze[x][y] == 1: return False # 判断当前位置是否已经在路径 if (x, y) in path: return False # 将当前位置加入路径 path.append((x, y)) # 判断当前位置是否是终点 if x == len(maze) - 1 and y == len(maze[0]) - 1: return True # 尝试向四个方向走 if find_path(x + 1, y, maze, path) or \ find_path(x - 1, y, maze, path) or \ find_path(x, y + 1, maze, path) or \ find_path(x, y - 1, maze, path): return True # 如果四个方向都走不通,则回溯到上一个位置 path.pop() return False # 测试代码 maze = [[0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]] path = [] find_path(0, 0, maze, path) print(path) ``` 2. 分枝界限法求迷宫路径: 分枝界限法求解迷宫路径的基本思路是将搜索空间划分为多个子空间,每个子空间对应一条路径,然后依次对每个子空间进行搜索,直到找到一条可行路径。具体实现可以使用队列或者堆栈保存待搜索的子空间,每次从队列或者堆栈取出一个子空间进行搜索,直到找到一条可行路径或者队列或者堆栈为空。代码如下: ```python from queue import PriorityQueue def find_path(maze): # 定义一个优先队列,用于保存待搜索的子空间 queue = PriorityQueue() queue.put((0, [(0, 0)])) while not queue.empty(): # 取出一个子空间进行搜索 _, path = queue.get() x, y = path[-1] # 判断当前位置是否是终点 if x == len(maze) - 1 and y == len(maze[0]) - 1: return path # 尝试向四个方向走 for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nx, ny = x + dx, y + dy # 判断新位置是否越界或者是障碍物 if nx < 0 or nx >= len(maze) or ny < 0 or ny >= len(maze[0]) or maze[nx][ny] == 1: continue # 判断新位置是否已经在路径 if (nx, ny) in path: continue # 计算新路径的代价(这里用路径长度作为代价) new_path = path + [(nx, ny)] cost = len(new_path) # 将新子空间加入优先队列 queue.put((cost, new_path)) return None # 测试代码 maze = [[0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]] path = find_path(maze) print(path) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值