【每日一题Day218】LC1091 二进制矩阵中的最短路径 | BFS

二进制矩阵中的最短路径【LC1091】

你驾驶出租车行驶在一条有 n 个地点的路上。这 n 个地点从近到远编号为 1n ,你想要从 1 开到 n ,通过接乘客订单盈利。你只能沿着编号递增的方向前进,不能改变方向。

乘客信息用一个下标从 0 开始的二维数组 rides 表示,其中 rides[i] = [starti, endi, tipi] 表示第 i 位乘客需要从地点 starti 前往 endi ,愿意支付 tipi 元的小费。

每一位 你选择接单的乘客 i ,你可以 盈利 endi - starti + tipi 元。你同时 最多 只能接一个订单。

给你 nrides ,请你返回在最优接单方案下,你能盈利 最多 多少元。

**注意:**你可以在一个地点放下一位乘客,并在同一个地点接上另一位乘客。

  • 思路

    常规BFS,使用队列进行BFS,搜索时记录搜索的轮数。搜索到一个可以访问的节点时,将其入队。如果搜索到终点时,直接返回当前轮数;如果队列为空仍为访问到终点,那么返回-1;

    • 访问过一个节点后,为了避免重复访问直接将给节点设置为-1
  • 实现

    class Solution {
          
          
        public int shortestPathBinaryMatrix(int[][] grid) {
          
          
            // BFS
           int[][] dirs = {
          
          {
          
          0, 1}, {
          
          1, 0}, {
          
          1, 1}, {
          
          0, -1}, {
          
          -1, 0}, {
          
          -1, -1}, {
          
          1, -1}, {
          
          -1, 1}};// 8个方向?
           Deque<int[]> queue = new LinkedList<>();
           int n = grid.length;
           int count = 0;
           if (grid[0][0] == 0){
          
          
               queue.add(new int[]{
          
          0, 0});
           }
           while(!queue.isEmpty()){
          
          
               int size = queue.size();
               count++;
               for (int i = 0; i < size; i++){
          
          
                    int[] p = queue.poll();
                    int x = p[0], y = p[1];
                    if (x == n - 1 && y == n - 1) return count;
                    for (int[] dir : dirs){
          
          
                        int x1 = x + dir[0], y1 = y + dir[1];           
                        if (x1 >= 0 && y1 >= 0 && x1 <n && y1 < n && grid[x1][y1] != 1){
          
                           
                            queue.add(new int[]{
          
          x1, y1});
                            grid[x1][y1] = 1;
                        }
                    }
               }
               
           }
           return -1;
    
        }
    }
    
    • 复杂度
      • 时间复杂度: O ( n 2 ) \mathcal{O}(n^2) O(n2)
      • 空间复杂度: O ( n 2 ) \mathcal{O}(n^2) O(n2)

猜你喜欢

转载自blog.csdn.net/Tikitian/article/details/130884199