P14326 [JOI2022 Preliminary Round 2] Carpet

Description

Bitaro, who loves fashion, bought a new carpet. The carpet is rectangular and is divided into a grid of $ H $ rows and $ W $ columns, and every cell is painted white or black. The color of the cell at the $ i $-th row from the top and the $ j $-th column from the left ($ 1 \le i \le H $, $ 1 \le j \le W $) is determined by the $ j $-th character of the string $ S_i $: if it is `.`, the cell is white; if it is `#`, the cell is black. Bitaro places a piece on the top-left cell of the carpet and imagines a game: by performing several operations, move the piece to the bottom-right cell of the carpet. - In each operation, the piece must move to one of the cells adjacent up, down, left, or right whose color is different from the color of the cell the piece is currently on. Bitaro wants to minimize the number of steps needed to reach the goal. However, depending on the pattern of the carpet, it may be impossible to reach the goal at all. Given the pattern of the carpet, write a program to determine whether the piece can be moved from the top-left cell to the bottom-right cell by repeating the operations, and if it can, find the minimum number of operations.

Input Format

The input is given from Standard Input in the following format: $ H $ $ W $ $ S_1 $ $ S_2 $ $ \vdots $ $ S_H $

Output Format

If the piece can reach the bottom-right cell from the top-left cell by repeating the operations, output the minimum number of operations; if it cannot, output $ -1 $. Output the result in a single line to Standard Output.

Explanation/Hint

### Sample 1 Explanation The following are two ways of moving that satisfy the requirements of the problem: :::align{center} ![](https://cdn.luogu.com.cn/upload/image_hosting/bvuzchox.png) ::: The way on the left needs only $9$ operations, while the way on the right needs $13$ operations. It can be shown that no way uses fewer than $9$ operations. ### Constraints - $ 1 \le H \le 500 $. - $ 1 \le W \le 500 $. - $ (H, W) \ne (1, 1) $. - $ S_i $ is a string of length $ W $ ($ 1 \le i \le H $). - Every character of $ S_i $ is `.` or `#` ($ 1 \le i \le H $). - $ H $ and $ W $ are integers. ### Subtasks 1. (4 points) $ H = 1 $. 2. (14 points) $ H \le 5 $, $ W \le 5 $. 3. (24 points) $ H \le 30 $, $ W \le 30 $. 4. (58 points) No additional constraints. Translated by QwenWork