首页 > 其他分享 >LeetCode 864. Shortest Path to Get All Keys

LeetCode 864. Shortest Path to Get All Keys

时间:2024-07-25 13:30:03浏览次数:7  
标签:keys Get Keys 864 int length grid key start

原题链接在这里:https://leetcode.com/problems/shortest-path-to-get-all-keys/description/

题目:

You are given an m x n grid grid where:

  • '.' is an empty cell.
  • '#' is a wall.
  • '@' is the starting point.
  • Lowercase letters represent keys.
  • Uppercase letters represent locks.

You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.

If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.

For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it is impossible, return -1.

Example 1:

Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.

Example 2:

Input: grid = ["@..aA","..B#.","....b"]
Output: 6

Example 3:

Input: grid = ["@Aa"]
Output: -1

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 30
  • grid[i][j] is either an English letter, '.''#', or '@'
  • There is exactly one '@' in the grid.
  • The number of keys in the grid is in the range [1, 6].
  • Each key in the grid is unique.
  • Each key in the grid has a matching lock.

题解:

The question asks for shortest path to find all the keys. When it is shortest path, we need to use BFS.

We maintain the state of the keys we already found, since we need it to know if we can open the lock we meet.

We use a integer to maintain the state of keys we already found. Each digit is 0, 1, representing if we see this key. 'a' is the last digit, 'b' is the second last digit.

In the BFS node, we need to have the coordinate x and y. Also we need to keys state.
Also we need to maintain a similar visited set for it.

Time Complexity: O(m * n * 2^k). m = grid.length. n = grid[0].length(). k is the number of keys. Since for each cell in the grid, there could be 2 ^ k possible key combinations.

Space: O(m * n * 2^k).

AC Java:

 1 class Solution {
 2     int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 3     public int shortestPathAllKeys(String[] grid) {
 4         int m = grid.length;
 5         int n = grid[0].length();
 6         int[] start = new int[3];
 7         int keys = 0;
 8         for(int i = 0; i < m; i++){
 9             for(int j = 0; j < n; j++){
10                 char c = grid[i].charAt(j);
11                 if(c == '@'){
12                     start[0] = i;
13                     start[1] = j;
14                 }else if(c >= 'a' && c <= 'z'){
15                     keys |= (1 << (c - 'a'));
16                 }
17             }
18         }
19 
20         LinkedList<int[]> que = new LinkedList<>();
21         HashSet<String> visited = new HashSet<>();
22         visited.add(start[0] + "," + start[1] + "," + start[2]);
23         que.add(start);
24 
25         int level = 0;
26         while(!que.isEmpty()){
27             int size = que.size();
28             while(size-- > 0){
29                 int[] cur = que.poll();
30                 if(cur[2] == keys){
31                     return level;
32                 }
33 
34                 for(int [] dir : dirs){
35                     int x = cur[0] + dir[0];
36                     int y = cur[1] + dir[1];
37                     int k = cur[2];
38                     if(x < 0 || x >= m || y < 0 || y >= n || grid[x].charAt(y) == '#'){
39                         continue;
40                     }
41 
42                     char c = grid[x].charAt(y);
43                     if(c >= 'A' && c <= 'Z' && ((k >> (c - 'A')) & 1) == 0){
44                         // no key yet
45                         continue;
46                     }
47 
48                     if(c >= 'a' && c <= 'z'){
49                         // found a key, update the key state
50                         k = k | (1 << (c - 'a'));
51                     }
52 
53                     String state = x + "," + y + "," + k;
54                     if(visited.contains(state)){
55                         continue;
56                     }
57 
58                     visited.add(state);
59                     que.add(new int[]{x, y, k});
60                 }
61             }
62 
63             level++;
64         }
65 
66         return -1;
67     }
68 }

 

标签:keys,Get,Keys,864,int,length,grid,key,start
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18322806

相关文章

  • Django request.data.get传送列表
    request.data.get('fa_no',[])代码片段通常用于Django处理视图中的传入请求数据。这一行代码试图从请求数据中获取键'fa_no'关联的值。如果在请求数据中未找到'fa_no',它会返回一个默认值空列表([])。以下是每个部分的解释:request:这是HTTP请求对象。data:这个属......
  • Django get_or_create和update_or_create 的作用和使用
    Djangoget_or_create和update_or_create的作用和使用:get_or_create和update_or_create是Django中的两个有用的方法,用于在数据库中获取或创建记录。如果记录不存在,则创建它们;如果存在,则返回现有记录。这两个方法帮助简化了避免重复记录的逻辑,并提供了一种简洁的方法来更新......
  • Python 中 __get__ 方法的内部原理
    我正在摆弄描述符,结果碰壁了。我以为我可以像使用任何其他方法一样直接调用它,但显然,它似乎不一致或者我遗漏了一些东西。假设我有一个用作描述符的坐标类:|||还有一个Point类,它有2个坐标属性:classCoordinate:def__set_name__(self,owner,name):self._na......
  • 在 python requests modul 中,如何检查页面是否使用“POST”方法或“GET”方法
    如何使用python“requests”模块检查页面是否使用“GET”方法或“POST”方法。我期望输出为True或False,或者GET或Post预期代码:importrequestsurl=f"www.get_example.com"response=requests.get(url)ifresponse.check_get==True:print("get")你......
  • Vue全家桶 - pinia 的理解和学习1(Pinia 核心概念的 Store、State、Getter、Action)
    Pinia(Vue的专属状态管理库)Pinia和Vuex的区别设计理念和架构Vuex采用集中式架构,所有状态存储在一个全局状态树中,通过mutations和actions来修改和处理状态。Pinia采用去中心化的架构,每个模块有自己的状态,这使得Pinia在代码分割和模块化方面更加灵活。TypeSc......
  • Linux获取线程调度策略pthread_attr_getschedpolicy
    thread_attr_getschedpolicy 函数是POSIX线程(pthread)库中用于获取线程属性对象中的调度策略的函数。在实时系统中,调度策略决定了线程如何被调度器选择来执行。pthread_attr_getschedpolicy 函数允许你查询一个已创建的线程属性对象(pthread_attr_t 类型)中设置的调度策略......
  • 用于 isinstance() 检查的 dict_keys 的显式 python3 类型是什么?
    在Python3中,我应该使用什么类型来检查字典键是否属于它?>>>d={1:2}>>>type(d.keys())<class'dict_keys'>所以我很自然地尝试了这个:>>>isinstance(d.keys(),dict_keys)Traceback(mostrecentcalllast):File"<stdin>",......
  • QListWidget实现内部拖动排序功能
    1.需求将QListWidget有很多的任务,需要拖动任务,手动进行排序,并且需要保存拖动之后的顺序,软件重新打开要是修改之后的顺序;(1)继承QListWidget,重写一个QListWidget自定义类#ifndefDROPLISTWIDGET_H#defineDROPLISTWIDGET_H#include<QListWidget>#include<QDropEvent>clas......
  • 为什么 Runtime.getRuntime().exec 在 Tomcat 中以 root 身份分叉进程?
    我正在使用Runtime.getRuntime().exec(...)从Tomcatweb应用程序中执行python脚本。当我在我的开发环境中时一切都很顺利(Eclipse通过Sysdeo-Plugin运行我的本地Tomcat(位于/home/me/opt/tomcat))。当我在生产环境(=DebianSqueeze)中运行我的web应用程序时,会出现此问题......
  • HttpClient 发送get和post请求的使用方法
    一Httpclient的简介    HttpClient是ApacheJakartaCommon下的子项目,可以用来提供高效的,最新的,功能丰富的支持HTTP协议的客户端变成工具包,并且他支持HTTP协议最新的版本和建议。核心API:HttpClient  HttpClientsCloseableHttpClientHttpGetHttpPost二Ht......