Shortest Path to Get All Keys, Hard Leetcode Problem

Problem is here: https://leetcode.com/problems/shortest-path-to-get-all-keys/description/:

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. 1 <= grid.length <= 30
  2. 1 <= grid[0].length <= 30
  3. grid[i][j] contains only '.''#''@''a'-'f' and 'A'-'F'
  4. The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.
I implemented it using Breadth-First-Search (BFS), but there is some caveats here:

  1. There is a state associated with each move. The state is the keys that you're carrying. It is important to keep passing this state as you move
  2. You're allowed to go back to a visited cell before, as long as the state is different. This is a key point
Other than that, this is the usual BFS. Solution is slow, but works. Code is down below, cheers.



public class Solution
{
 public int ShortestPathAllKeys(string[] grid)
 {
  if (grid == null) return -1;

  //Find the start and number of keys
  int targetKeys = 0;
  int startRow = -1;
  int startCol = -1;
  for (int r = 0; r < grid.Length; r++)
  {
   //Console.WriteLine(grid[r]);
   for (int c = 0; c < grid[0].Length; c++)
   {
    if (grid[r][c] == '@')
    {
     startRow = r;
     startCol = c;
    }
    if (grid[r][c] >= 'a' && grid[r][c] <= 'f') targetKeys++;
   }
  }
  //Console.WriteLine();

  //Process BFS
  Queue queue = new Queue();
  Hashtable visited = new Hashtable();
  QueueItem qi = new QueueItem(startRow, startCol, '@', 0, null, 0);
  visited.Add(qi.HashTableKey(), true);
  queue.Enqueue(qi);

  while (queue.Count > 0)
  {
   QueueItem cqi = (QueueItem)queue.Dequeue();
   //Console.WriteLine("Current = (pos=({0},{1}), key={2}, moves={3})", cqi.row, cqi.col, cqi.HashTableKey(), cqi.moves);
   //Console.ReadLine();

   if (cqi.HaveAllKeys(targetKeys)) return cqi.moves;

   int[] deltaRows = { -1, 1, 0, 0 };
   int[] deltaCols = { 0, 0, -1, 1 };

   for (int i = 0; i < deltaRows.Length; i++)
   {
    int dr = deltaRows[i] + cqi.row;
    int dc = deltaCols[i] + cqi.col;

    if (dr >= 0 &&
     dr < grid.Length &&
     dc >= 0 &&
     dc < grid[0].Length &&
     grid[dr][dc] != '#')
    {
     QueueItem nqi = new QueueItem(dr, dc, grid[dr][dc], cqi.moves + 1, cqi.keys, cqi.keysAcquired);
     if (nqi.CanUnlock(grid[dr][dc]) && !visited.ContainsKey(nqi.HashTableKey()))
     {
      visited.Add(nqi.HashTableKey(), true);
      queue.Enqueue(nqi);
     }
    }
   }
  }

  return -1;
 }
}

public class QueueItem
{
 public int row = 0;
 public int col = 0;
 public int[] keys = new int[6];
 public int moves = 0;
 public int keysAcquired = 0;

 public QueueItem(int row, int col, char key, int moves, int[] previousKeys, int previousKeysAcquired)
 {
  this.row = row;
  this.col = col;
  if (previousKeys != null) keys = (int[])previousKeys.Clone();
  if (previousKeysAcquired != -1) keysAcquired = previousKeysAcquired;
  if(key >= 'a' && key <= 'f' && keys[(int)(key - 'a')] == 0)
  {
   keys[(int)(key - 'a')] = 1;
   keysAcquired++;
  }
  this.moves = moves;
 }

 public string HashTableKey()
 {
  string key = "";

  key += row.ToString();
  key += "@";
  key += col.ToString();
  key += "@";
  for (int i = 0; i < keys.Length; i++)
   key += keys[i].ToString();

  return key;
 }

 public bool HaveAllKeys(int targetKeys)
 {
  return keysAcquired == targetKeys;
 }

 public bool CanUnlock(char l)
 {
  if (l >= 'A' && l <= 'F')
   return keys[(int)(l - 'A')] == 1;
  return true;
 }
}

Comments

  1. This one was fun :)

    import collections

    DIRECTIONS = (-1, 0, 1, 0, -1)

    class Solution:
    def shortestPathAllKeys(self, grid):
    """
    :type grid: List[str]
    :rtype: int
    """
    N, M = len(grid), len(grid[0])
    x, y, required_keys = -1, -1, 0
    for i in range(N):
    for j in range(M):
    if grid[i][j] == "@":
    x, y = i, j
    elif grid[i][j].islower():
    required_keys += 1
    queue = collections.deque()
    initial_state = x, y, ""
    queue.append(initial_state)
    states = set(queue)
    levels = 0
    while queue:
    for _ in range(len(queue)):
    x, y, keys = queue.popleft()
    if grid[x][y].islower() and grid[x][y] not in keys:
    keys += grid[x][y]
    if len(keys) == required_keys:
    return levels
    for i in range(len(DIRECTIONS)-1):
    new_x = x + DIRECTIONS[i]
    new_y = y + DIRECTIONS[i+1]
    if 0 <= new_x < N and 0 <= new_y < M and (grid[new_x][new_y] in ".abcdef@" or grid[new_x][new_y].lower() in keys) and (new_x, new_y, keys) not in states:
    new_state = new_x, new_y, keys
    queue.append(new_state)
    states.add(new_state)
    levels += 1
    return -1

    ReplyDelete

Post a Comment

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Advent of Code - Day 7, 2024: Backtracking and Eval

Golang vs. C#: performance characteristics (simple case study)