<p>You are given an <code>m x n</code> grid <code>grid</code> where:</p>

<ul>
	<li><code>&#39;.&#39;</code> is an empty cell.</li>
	<li><code>&#39;#&#39;</code> is a wall.</li>
	<li><code>&#39;@&#39;</code> is the starting point.</li>
	<li>Lowercase letters represent keys.</li>
	<li>Uppercase letters represent locks.</li>
</ul>

<p>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.</p>

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

<p>For some <code><font face="monospace">1 &lt;= k &lt;= 6</font></code>, there is exactly one lowercase and one uppercase letter of the first <code>k</code> 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.</p>

<p>Return <em>the lowest number of moves to acquire all keys</em>. If it is impossible, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg" style="width: 404px; height: 245px;" />
<pre>
<strong>Input:</strong> grid = [&quot;@.a..&quot;,&quot;###.#&quot;,&quot;b.A.B&quot;]
<strong>Output:</strong> 8
<strong>Explanation:</strong> Note that the goal is to obtain all the keys not to open all the locks.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg" style="width: 404px; height: 245px;" />
<pre>
<strong>Input:</strong> grid = [&quot;@..aA&quot;,&quot;..B#.&quot;,&quot;....b&quot;]
<strong>Output:</strong> 6
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg" style="width: 244px; height: 85px;" />
<pre>
<strong>Input:</strong> grid = [&quot;@Aa&quot;]
<strong>Output:</strong> -1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 30</code></li>
	<li><code>grid[i][j]</code> is either an English letter, <code>&#39;.&#39;</code>, <code>&#39;#&#39;</code>, or <code>&#39;@&#39;</code>.&nbsp;</li>
	<li>There is exactly one&nbsp;<code>&#39;@&#39;</code>&nbsp;in the grid.</li>
	<li>The number of keys in the grid is in the range <code>[1, 6]</code>.</li>
	<li>Each key in the grid is <strong>unique</strong>.</li>
	<li>Each key in the grid has a matching lock.</li>
</ul>

from collections import deque
class Solution:
    def shortestPathAllKeys(self, grid: List[str]) -> int:
        #run a bfs, but the state is [i][j][mask] where mask is a bitmask representing whether each key has been "picked up" or not
        startingRow = 0
        startingCol = 0
        keyCount = 0
        #iterate over the grid and find starting position and all the keys
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == '@':
                    startingRow = i
                    startingCol = j
                elif grid[i][j] != '.' and grid[i][j] != '#':
                    keyCount += 1
        keyCount //= 2
        #perform bfs starting at the startingRow/startingCol. here mask is 0 since no keys are picked up
        queue = deque()
        queue.append([startingRow, startingCol, 0])
        rowDir = [0, 1, 0, -1]
        colDir = [1, 0, -1, 0]
        visited = set()
        dist = {}
        dist[(startingRow, startingCol, 0)] = 0
        visited.add((startingRow, startingCol, 0))
        ans = 10000000000
        while len(queue) > 0:
            currState = queue.popleft()
            row = currState[0]
            col = currState[1]
            mask = currState[2]
            allKeys = True
            for i in range(keyCount):
                if mask & (1 << i) == 0:
                    allKeys = False
            if allKeys:
                ans = min(ans, dist[(row, col, mask)])
            for i in range(4):
                newRow = row+rowDir[i]
                newCol = col+colDir[i]
                
                #out of bounds
                if newRow < 0 or newRow >= len(grid) or newCol < 0 or newCol >= len(grid[0]):
                    continue
                elif grid[newRow][newCol] == '#': 
                    #if wall
                    continue
                elif ord(grid[newRow][newCol]) >= 65 and ord(grid[newRow][newCol]) <= 90 and mask & (1 << (ord(grid[newRow][newCol]) - ord('A'))) == 0:
                    #if lock but we don't have key
                    continue
                keyVal = -1
                if ord(grid[newRow][newCol]) >= 97 and ord(grid[newRow][newCol]) <= 122:
                    keyVal = ord(grid[newRow][newCol]) - ord('a')
                #print(keyVal)
                newMask = mask
                if keyVal != -1:
                    newMask = mask | (1 << keyVal)
                    #print(newMask)
                if (newRow, newCol, newMask) not in visited:
                    visited.add((newRow, newCol, newMask))
                    dist[(newRow, newCol, newMask)] = dist[(row, col, mask)]+1
                    queue.append((newRow, newCol, newMask))
        if ans == 10000000000:
            return -1
        return ans
                
                






27898