> For the complete documentation index, see [llms.txt](https://wentao-shao.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wentao-shao.gitbook.io/leetcode/graph-search/864.shortest-path-to-get-all-keys.md).

# 864.Shortest-Path-to-Get-All-Keys

## 864. Shortest Path to Get All Keys

## 题目地址

<https://leetcode.com/problems/shortest-path-to-get-all-keys/>

## 题目描述

```
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions.  We cannot walk outside the grid, or walk into a wall.  If we walk over a key, we pick it up.  We can't walk over a lock unless we have the 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's impossible, return -1.

Example 1:
Input: ["@.a.#","###.#","b.A.B"]
Output: 8

Example 2:
Input: ["@..aA","..B#.","....b"]
Output: 6

Note:
1 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.
```

## 代码

### Approach #1 BFS

Time: `O(mn2^k)` && Space: O(1)

```java
class Solution {

    class State {
        int x;
        int y;
        int key;
        public State(int x, int y, int key) {
            this.x = x;
            this.y = y;
            this.key = key;
        }
    }

    int[][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    public int shortestPathAllKeys(String[] grid) {
        int x = 0;
        int y = 0;
        int n = grid.length;
        int m = grid[0].length(); 
        int keyCount = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                char c = grid[i].charAt(j);
                if (c == '@') {
                    x = i;
                    y = j;
                }

                 if (c >= 'a' && c <= 'f') {
                     keyCount = Math.max(keyCount, c - 'a' + 1);
                 }    

            }
        }

        HashSet<String> visited = new HashSet();
        Queue<State> queue = new LinkedList();
        queue.add(new State(x, y, 0));
        visited.add(x + " " + y + " " + 0);
        int step = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int k = 0; k < size; k++) {
                State cur = queue.poll();
                if (cur.key == (1 << keyCount) - 1) return step;
                for (int[] dir: dirs) {
                    int i = cur.x + dir[0];
                    int j = cur.y + dir[1];

                    if (i < 0 || i >= n || j < 0 || j >= m) {
                        continue;
                    }

                    char c = grid[i].charAt(j);
                    int key = cur.key;
                    if (c == '#') {
                        continue;
                    }

                    if (c >= 'a' && c <= 'f') {
                        key |=  (1 << (c - 'a'));
                    }

                    if (c >= 'A' && c <= 'F' 
                        && (cur.key >> (c  - 'A') & 1) == 0) {
                        continue;
                    }

                    if (!visited.contains(i + " " + j + " " + key)) {
                        queue.add(new State(i, j, key));
                        visited.add(i + " " + j + " " + key);
                    }
                }
            }
            step++;
        }


        return -1;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/graph-search/864.shortest-path-to-get-all-keys.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
