首页 > 其他分享 >LeetCode 1778. Shortest Path in a Hidden Grid

LeetCode 1778. Shortest Path in a Hidden Grid

时间:2024-03-24 10:12:27浏览次数:23  
标签:Grid target int 1778 robot cell grid master Path

原题链接在这里:https://leetcode.com/problems/shortest-path-in-a-hidden-grid/description/

题目:

This is an interactive problem.

There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

You want to find the minimum distance to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

Thr GridMaster class has the following functions:

  • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
  • void move(char direction) Moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, and the robot will remain in the same position.
  • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.

Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.

Return the minimum distance between the robot's initial starting cell and the target cell. If there is no valid path between the cells, return -1.

Custom testing:

The test input is read as a 2D matrix grid of size m x n where:

  • grid[i][j] == -1 indicates that the robot is in cell (i, j) (the starting cell).
  • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
  • grid[i][j] == 1 indicates that the cell (i, j) is empty.
  • grid[i][j] == 2 indicates that the cell (i, j) is the target cell.

There is exactly one -1 and 2 in grid. Remember that you will not have this information in your code.

Example 1:

Input: grid = [[1,2],[-1,0]]
Output: 2
Explanation: One possible interaction is described below:
The robot is initially standing on cell (1, 0), denoted by the -1.
- master.canMove('U') returns true.
- master.canMove('D') returns false.
- master.canMove('L') returns false.
- master.canMove('R') returns false.
- master.move('U') moves the robot to the cell (0, 0).
- master.isTarget() returns false.
- master.canMove('U') returns false.
- master.canMove('D') returns true.
- master.canMove('L') returns false.
- master.canMove('R') returns true.
- master.move('R') moves the robot to the cell (0, 1).
- master.isTarget() returns true. 
We now know that the target is the cell (0, 1), and the shortest path to the target cell is 2.

Example 2:

Input: grid = [[0,0,-1],[1,1,1],[2,0,0]]
Output: 4
Explanation: The minimum distance between the robot and the target cell is 4.

Example 3:

Input: grid = [[-1,0],[0,2]]
Output: -1
Explanation: There is no path from the robot to the target cell. 

Constraints:

  • 1 <= n, m <= 500
  • m == grid.length
  • n == grid[i].length
  • grid[i][j] is either -101, or 2.
  • There is exactly one -1 in grid.
  • There is exactly one 2 in grid.

题解:

When talking about shortest path, it is BFS.

But here it doesn't have the board, it only has a GridMaster with move functions that is like DFS.

Thus first perform DFS to find the target. Mark the block, path and target for each grid.

Then perform BFS from the same start position and find the position.

Time Complexity: O(N^2). N is the lenght of grid. 

Space: O(N^2).

AC Java:

 1 /**
 2  * // This is the GridMaster's API interface.
 3  * // You should not implement it, or speculate about its implementation
 4  * class GridMaster {
 5  *     boolean canMove(char direction);
 6  *     void move(char direction);
 7  *     boolean isTarget();
 8  * }
 9  */
10 
11 class Solution {
12     char [] forward = {'U','D','L','R'};
13     char [] backward = {'D','U','R','L'};
14     int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
15     int unvisited = 0;
16     int path = 1;
17     int block = -1;
18     int target = 2;
19     public int findShortestPath(GridMaster master) {
20         int N = 501;
21         int[][] grid = new int[2*N][2*N];
22         dfs(N, N, master, grid);
23         if(grid[N][N] == target){
24             return 0;
25         }
26 
27         LinkedList<int[]> que = new LinkedList<>();
28         que.add(new int[]{N, N});
29         boolean[][] visited = new boolean[2*N][2*N];
30         grid[N][N] = block;
31         int level = 0;
32         while(!que.isEmpty()){
33             int size = que.size();
34             while(size-- > 0){
35                 int [] cur = que.poll();
36 
37                 for(int i = 0; i < 4; i++){
38                     int p = cur[0] + dirs[i][0];
39                     int q = cur[1] + dirs[i][1];
40                     if(grid[p][q] == target){
41                         return level + 1;
42                     }
43                     if(grid[p][q] == block){
44                         continue;
45                     }
46 
47                     que.add(new int[]{p, q});
48                     grid[p][q] = block;
49                 }
50             }
51 
52             level++;
53         }
54 
55         return -1;
56     }
57 
58     private void dfs(int r, int c, GridMaster master, int[][] grid){
59         if(grid[r][c] != unvisited){
60             return;
61         }
62 
63         if(master.isTarget()){
64             grid[r][c] = target;
65         }else{
66             grid[r][c] = path;
67         }
68 
69         for(int i = 0; i < 4; i++){
70             char f = forward[i];
71             char b = backward[i];
72             int p = r + dirs[i][0];
73             int q = c + dirs[i][1];
74 
75             if(!master.canMove(f)){
76                 grid[p][q] = block;
77             }else{
78                 master.move(f);
79                 dfs(p, q, master, grid);
80                 master.move(b);
81             }
82         }
83     }
84 }

 

标签:Grid,target,int,1778,robot,cell,grid,master,Path
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18092116

相关文章

  • 【发疯毕设日志day7】hagrid_dataset_512数据集作者论文原文逐句翻译——大疆tello手
    论文原文::::2206.08219.pdf(arxiv.org)https://arxiv.org/pdf/2206.08219.pdf摘要     本文介绍了一个庞大的手势识别数据集——海格(HAndGestrueRecognitionImagedataset),以简历一个手势识别(HGR)系统,专注于与设备的交互管理。这就是为什么所选的18个手势都呗赋予......
  • xpath和contains模糊匹配
    来源:https://www.cnblogs.com/kaibindirver/p/12072546.html最近在弄数据爬取,研究了下xpath,也参考了很多文章,这篇总结不错,就直接复制过来了。xpath可以以标签定位,也可以@任意属性:如:以input标签定位:driver.find_element_by_xpath("//input[@id='kw']")如:@type属性:driver.find_......
  • 解决出现javax.net.ssl.SSLHandshakeException: PKIX path building failed 或 sun.se
    From: https://www.cnblogs.com/luoxiao1104/p/16671501.html当我们从网络上根据url下载文件的时候可能会出现一下异常错误信息: javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:......
  • 分享一个自己写的wpf的datagrid分页工具
    <StackPanelHorizontalAlignment="Center"><DataGridx:Name="datagrid1"AutoGenerateColumns="False"CanUserAddRows="False"Height="200"Margin="0,10">......
  • leetcode 路经总和 pathsum
    很熟悉的一道题,XX二面做过,面试官没让我当场造树,让我用数组模拟树来运行,依旧跑出来了。但是刚刚再做了一下,没思路,不会写......
  • [CF845G] Shortest Path Problem? 题解
    [CF845G]ShortestPathProblem?题解注意到如果我们在路径中多走了一个环,那么得到的贡献就是这个环的贡献。对于这种有关环的问题,考虑一棵生成树,这样所有环都可以用一条祖先边和一些树边组成,发现选环走的过程是独立的,考虑把所有环的权值丢进线性基里,然后查询xordist[1]^xor......
  • StringGrid1做数据控件的基本常用操作
    procedureTForm1.StringGrid1SelectCell(Sender:TObject;ACol,ARow:Integer;varCanSelect:Boolean);varR:TRect;org:TPoint;beginifARow>0thenbegin//标题行不能修改ifnotSQLResutIsEmptythenbeginwithSenderasTStringGriddoif......
  • Go环境变量配置,及GOROOT、GOPATH的区别
    一、安装Gogo下载地址:https://golang.google.cn/dl/windows下载安装,有两种方式。解压和直接安装方式一:直接下载安装包。以.msi结尾的文件。例如:go1.22.1.windows-amd64.msi 下载后,双击后一直点下一步即可安装成功。方式二:下载压缩包文件,直接解压。解压后配置环境变量......
  • Go语言GOPATH是什么
    在Go语言中,GOPATH是一个环境变量,用于指定Go语言的工作空间路径。它是Go语言中一个重要的概念,用于管理和组织你的Go项目。GOPATH指定了Go语言的工作目录,它包含了三个重要的子目录:src、pkg和bin。这些子目录分别用于存放源代码文件、编译后的包文件和可执行文件。当你使用go......
  • mongo GridFSBucket
    1、描述:mongo  单机使用 GridFSBucket2、pox中添加jar<dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.12.9</version></dependency>3、module中使用,直接上代码 3.1......