#abc283e. E - Don't Isolate Elements

E - Don't Isolate Elements

Score : 500500 points

问题描述

你得到一个矩阵 AA,它有 HH 行和 WW 列。其每个元素的值为 0011。对于满足条件 1iH1 \leq i \leq H1jW1 \leq j \leq W 的整数对 (i,j)(i, j),我们用 Ai,jA_{i,j} 表示第 ii 行第 jj 列的元素。

你可以对矩阵 AA 执行以下操作任意多次(可能为零次):

  • 选择一个满足 1iH1 \leq i \leq H 的整数 ii。对于每一个满足 1jW1 \leq j \leq W 的整数 jj,将 Ai,jA_{i,j} 的值替换为 1Ai,j1-A_{i,j}

Ai,jA_{i,j} 满足以下条件,则称其为 孤立元素:不存在与其相邻且具有相同值的元素;换句话说,如果不存在四个整数对 (x,y)=(i1,j),(i+1,j),(i,j1),(i,j+1)(x,y) = (i-1,j),(i+1,j),(i,j-1),(i,j+1) 满足 1xH,1yW1 \leq x \leq H, 1 \leq y \leq W 以及 Ai,j=Ax,yA_{i,j} = A_{x,y}

确定是否可以通过重复执行上述操作,使得矩阵 AA 处于没有孤立元素的状态。如果可能,请找到完成此目标所需的最少操作次数。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You are given a matrix AA with HH rows and WW columns. The value of each of its elements is 00 or 11. For an integer pair (i,j)(i, j) such that 1iH1 \leq i \leq H and 1jW1 \leq j \leq W, we denote by Ai,jA_{i,j} the element at the ii-th row and jj-th column.

You can perform the following operation on the matrix AA any number of times (possibly zero):

  • Choose an integer ii such that 1iH1 \leq i \leq H. For every integer jj such that 1jW1 \leq j \leq W, replace the value of Ai,jA_{i,j} with 1Ai,j1-A_{i,j}.

Ai,jA_{i,j} is said to be isolated if and only if there is no adjacent element with the same value; in other words, if and only if none of the four integer pairs (x,y)=(i1,j),(i+1,j),(i,j1),(i,j+1)(x,y) = (i-1,j),(i+1,j),(i,j-1),(i,j+1) satisfies 1xH,1yW1 \leq x \leq H, 1 \leq y \leq W, and Ai,j=Ax,yA_{i,j} = A_{x,y}.

Determine if you can make the matrix AA in such a state that no element is isolated by repeating the operation. If it is possible, find the minimum number of operations required to do so.

Constraints

  • 2H,W10002 \leq H,W \leq 1000
  • Ai,j=0A_{i,j} = 0 or Ai,j=1A_{i,j} = 1
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

HH WW

A1,1A_{1,1} A1,2A_{1,2} \ldots A1,WA_{1,W}

A2,1A_{2,1} A2,2A_{2,2} \ldots A2,WA_{2,W}

\vdots

AH,1A_{H,1} AH,2A_{H,2} \ldots AH,WA_{H,W}

Output

If you can make it in such a state that no element is isolated by repeating the operation, print the minimum number of operations required to do so; otherwise, print -1.

Sample Input 1

3 3
1 1 0
1 0 1
1 0 0

Sample Output 1

1

An operation with i=1i = 1 makes A=((0,0,1),(1,0,1),(1,0,0))A = ((0,0,1),(1,0,1),(1,0,0)), where there is no longer an isolated element.

Sample Input 2

4 4
1 0 0 0
0 1 1 1
0 0 1 0
1 1 0 1

Sample Output 2

2

Sample Input 3

2 3
0 1 0
0 1 1

Sample Output 3

-1

update @ 2024/3/10 11:52:37