Class Solution

java.lang.Object
g0701_0800.s0752_open_the_lock.Solution

public class Solution extends Object
752 - Open the Lock.<p>Medium</p> <p>You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: <code>'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'</code>. The wheels can rotate freely and wrap around: for example we can turn <code>'9'</code> to be <code>'0'</code>, or <code>'0'</code> to be <code>'9'</code>. Each move consists of turning one wheel one slot.</p> <p>The lock initially starts at <code>'0000'</code>, a string representing the state of the 4 wheels.</p> <p>You are given a list of <code>deadends</code> dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.</p> <p>Given a <code>target</code> representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> deadends = [&ldquo;0201&rdquo;,&ldquo;0101&rdquo;,&ldquo;0102&rdquo;,&ldquo;1212&rdquo;,&ldquo;2002&rdquo;], target = &ldquo;0202&rdquo;</p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>A sequence of valid moves would be &ldquo;0000&rdquo; -> &ldquo;1000&rdquo; -> &ldquo;1100&rdquo; -> &ldquo;1200&rdquo; -> &ldquo;1201&rdquo; -> &ldquo;1202&rdquo; -> &ldquo;0202&rdquo;.</p> <p>Note that a sequence like &ldquo;0000&rdquo; -> &ldquo;0001&rdquo; -> &ldquo;0002&rdquo; -> &ldquo;0102&rdquo; -> &ldquo;0202&rdquo; would be invalid,</p> <p>because the wheels of the lock become stuck after the display becomes the dead end &ldquo;0102&rdquo;.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> deadends = [&ldquo;8888&rdquo;], target = &ldquo;0009&rdquo;</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong> We can turn the last wheel in reverse to move from &ldquo;0000&rdquo; -> &ldquo;0009&rdquo;.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> deadends = [&ldquo;8887&rdquo;,&ldquo;8889&rdquo;,&ldquo;8878&rdquo;,&ldquo;8898&rdquo;,&ldquo;8788&rdquo;,&ldquo;8988&rdquo;,&ldquo;7888&rdquo;,&ldquo;9888&rdquo;], target = &ldquo;8888&rdquo;</p> <p><strong>Output:</strong> -1</p> <p><strong>Explanation:</strong> We cannot reach the target without getting stuck.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= deadends.length <= 500</code></li> <li><code>deadends[i].length == 4</code></li> <li><code>target.length == 4</code></li> <li>target <strong>will not be</strong> in the list <code>deadends</code>.</li> <li><code>target</code> and <code>deadends[i]</code> consist of digits only.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • openLock

      public int openLock(String[] deadEnds, String target)