#t453. 走迷宫

走迷宫

Walking the Maze

Problem Background

Special for beginners, ^_^

Problem Description

A maze consists of a grid of RR rows and CC columns. Some cells contain obstacles and cannot be entered; the others are open ground and can be walked on.

Given a maze, find the minimum number of steps from the top-left cell to the bottom-right cell (the data guarantees a path always exists). You may only move horizontally or vertically, never diagonally.

Input Format

The first line contains two integers, RR and CC, the height and width of the maze (1≤R,C≤401 \le R, C \le 40).

Then follow RR lines, each with CC characters, describing the whole maze.

  • . denotes an open cell.
  • # denotes a cell with an obstacle.

The top-left and bottom-right cells are both ..

Output Format

Print the minimum number of cells (open cells) that must be passed through from the top-left to the bottom-right, counting both the start and the end cells.

Sample Input

5 5
..###
#....
#.#.#
#.#.#
#.#..

Sample Output

9

Constraints

1≤R,C≤401 \le R, C \le 40.

Time limit 11 s, memory 10241024 KiB per test case.

Hint

  • A plain 2D BFS (or even 0-1 BFS) gives the shortest path; every step costs 1, so the first time you reach the bottom-right is the answer.
  • "Counting the start and end" means a BFS that records distance, starting at distance 11 for the source, will print exactly what is asked.