QOJ.ac

QOJ

Límite de tiempo: 1 s Límite de memoria: 128 MB

#23585. 網格遊戲

Estadísticas

Taeyang 用放在 $M\times N$ 網格上的 $MN$ 顆黑白棋子開始遊戲,如下圖所示。

problem_23585_ec8131d293e484e99357a6f8c0e3b23b.png

對於任意棋子 $X$,把它上、下、左、右相鄰的 $4$ 顆棋子稱為 $X$ 的鄰居。Taeyang 可以選擇一顆棋子改變其顏色。這顆棋子原先同色的鄰居也會變成新的顏色。這個過程會不斷重複:發生變色的棋子的鄰居中,原先同色的棋子也會變色。

例如,將上圖中的棋子 $A$ 變為白色後,呈「ㄷ」字形的黑色棋子都會變為白色,結果如下圖所示。

problem_23585_d0af010b6c22f49813a5605257b3100e.png

接著將棋子 $C$ 變為白色,結果如下圖所示。

problem_23585_74fc41bf0baf75fc892172fac72f2399.png

然後將棋子 $F$ 變為白色,最後將棋子 $E$ 變為白色,所有棋子就都變成白色了。因此,一共進行了四次變色,使所有棋子變為白色。

不過,只需兩次變色就能使所有棋子顏色相同。先將棋子 $B$ 變為黑色,結果如下圖所示。

problem_23585_e01e672992b8f344cec71a0526f0d1b5.png

之後,可以將棋子 $A$ 變為白色,使所有棋子都變為白色;也可以將棋子 $D$ 變為黑色,使所有棋子都變為黑色。因此,只進行了兩次變色,就使所有棋子顏色相同。

給定 $M\times N$ 網格上的黑白棋子,編寫一個程式,求使所有棋子顏色相同所需的最少變色次數。

輸入格式

第一行給出表示 $M\times N$ 網格的兩個正整數 $M$ 和 $N$,以空格分隔。$M$ 和 $N$ 均在 $2$ 到 $100$ 之間,包含兩端。從第二行開始的 $M$ 行中,每行給出 $N$ 個以空格分隔的數,表示網格中的一行:$0$ 表示白色棋子,$1$ 表示黑色棋子。

輸出格式

第一行輸出使所有棋子顏色相同所需的最少變色次數。

範例

輸入格式 1

5 6
1 1 0 1 0 0
1 0 0 1 1 1
1 1 0 1 1 1
0 0 0 0 0 0
1 1 1 0 1 1

輸出格式 1

2

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.