#P3956. [NOIP 2017 普及组] 棋盘
[NOIP 2017 普及组] 棋盘
Description
There is an chessboard. Each cell on the board may be red, yellow, or colorless. You need to go from the top-left corner of the board to the bottom-right corner.
At any moment, the cell you stand on must be colored (not colorless). You can move only in four directions: up, down, left, and right. When you move from one cell to another, if the two cells have the same color, you do not need to spend any coins; if the colors are different, you need to spend coin.
In addition, you can spend coins to cast a spell to temporarily change the next colorless cell into a color you choose. But this spell cannot be used consecutively, and its duration is short. That is, if you use this spell and step onto this temporarily colored cell, you cannot use the spell again; only when you leave this position and step onto a cell that originally has a color can you use the spell again. When you leave the cell that was made colored by the spell, it reverts to colorless.
Now you need to go from the top-left corner to the bottom-right corner of the board. Find the minimum number of coins required.
Input Format
The first line contains two positive integers , separated by a space, which denote the size of the board and the number of colored cells, respectively.
The next lines each contain three integers , indicating that the cell at coordinates has color .
Here, means yellow, and means red. Adjacent numbers are separated by a space. The top-left corner has coordinates , and the bottom-right corner has coordinates .
All other cells on the board are colorless. It is guaranteed that the top-left corner is colored.
Output Format
Output a single integer, the minimum number of coins required. If it is impossible to reach the destination, output -1.
5 7
1 1 0
1 2 0
2 2 1
3 3 1
3 4 0
4 4 1
5 5 0
8
5 5
1 1 0
1 2 0
2 2 1
3 3 1
5 5 0
-1
Hint
Explanation for Sample 1
The board’s colors are as shown in the table below, where blank cells are colorless.
Start from and move to without spending coins.
Move from down to , spending coin.
Cast the spell at to make yellow, spending coins.
Move from to without spending coins.
Move from to without spending coins.
Move from to , spending coin.
Move from to , spending coin.
Cast the spell at to make yellow, spending coins.
Move from to without spending coins.
Move from to , spending coin.
A total of coins are spent.
Explanation for Sample 2
The board’s colors are as shown in the table below, where blank cells are colorless.
From to , spend no coins.
From to , spend coin.
Cast the spell to make yellow, and move from to , spending coins.
From to , spend no coins.
From , you can only cast the spell to reach .
From none of these four cells can you reach , so it is impossible to reach the destination, and the output is .
Constraints
For of the testdata, .
For of the testdata, .
For of the testdata, .
Translated by ChatGPT 5
京公网安备 11011102002149号