Ctrl K

Corner to Corner Like a King

Medium
You get a square grid grid of size n × n, where 0 is a free cell and 1 is a wall. Walk from the top-left corner (0, 0) to the bottom-right corner (n - 1, n - 1), stepping only on free cells. In one step you may move to any of the eight neighbouring cells, through a side or a corner, like a king in chess. The length of a path is the number of cells on it, counting the first and the last. Return the length of the shortest path, or -1 if there is none (including when either corner is a wall).
Example 1
grid=[[0, 0, 1], [1, 0, 1], [1, 1, 0]] → 3

The path (0, 0) → (1, 1) → (2, 2) moves diagonally and visits 3 cells.

Example 2
grid=[[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 0, 1], [1, 0, 1, 0]] → 6

Go down the left column to (2, 0), then diagonally to (3, 1), (2, 2) and (3, 3): 6 cells in total.

Example 3
grid=[[0, 1], [1, 1]] → -1

The bottom-right corner is blocked, so there is no path and the answer is -1.

Constraints
  • n == len(grid) == len(grid[i])
  • 1 ≤ n ≤ 100
  • grid[i][j] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrain the Landlocked Ponds MediumLand Regions on a Map MediumSteps to the Nearest Exit MediumRain Reaching Both Seas MediumCan the Ball Stop at the Target Medium
loading Python…
Input
grid=[[0, 0, 1], [1, 0, 1], [1, 1, 0]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 65 tests on the server, hidden ones included.