Leetcode Problem 864. Shortest Path to Get All Keys
864. Shortest Path to Get All Keys
Leetcode Solutions
Breadth-First Search with State Encoding
Initialize a queue and a set to keep track of visited states.
Find the starting position and initialize the starting state with no keys collected.
Add the starting position and state to the queue.
While the queue is not empty, perform the following steps:
a. Dequeue the current state from the queue.
b. If the current state has all keys, return the number of moves made.
c. For each possible move (up, down, left, right), check if the move is valid (not a wall, within bounds).
d. If the move leads to a key, update the state by adding the key.
e. If the move leads to a lock, check if the corresponding key is collected.
f. If the move is valid and the new state has not been visited, add it to the queue and mark it as visited.
If all states have been visited or no path exists, return -1.