Diagonal Flipping

시간 제한1초메모리 제한2048 MB

요약
0과 1로 이루어진 격자가 주어질 때, 두 방향의 대각선 뒤집기를 최소 몇 번 해야 모든 칸을 0으로 만들 수 있는지 구하고, 불가능하면 -1을 출력합니다.
난이도

보통10점 중 7점

유형
그리디, 구현, 배열
정답자
아직 제출이 없습니다

문제

We are given an m×nm \times n grid that consists of 00s and 11s. We have two types of diagonal operations like the following two figures. The type AA diagonal flipping operation to a grid position (i,j)(i,j) is to flip all the elements in the positions (i+k,j−k)(i + k,j - k) of the grid for any integer kk. If we flip the element 00, then it becomes 11. If we flip the element 11, then it becomes 00. The type BB diagonal flipping operation to a grid position (i,j)(i,j) is to flip all the elements in the positions (i+k,j+k)(i + k,j + k) of the grid for any integer kk. Note that a grid position (p,q)(p, q) is valid only when 0≤p≤m−10 ≤ p ≤ m - 1, 0≤q≤n−10 ≤ q ≤ n - 1.

Fig 1. Type AA diagonal operation to the grid position (2,0)(2, 0)

Fig 2. Type BB diagonal operation to the grid position (2,1)(2, 1)

Fig 1 shows the type AA diagonal flipping operation to the grid position (2,0)(2, 0). Note that the type AA diagonal flipping operations to the grid positions (1,1)(1, 1) or (0,2)(0, 2) have the same effect. Fig 2 shows the type BB diagonal flipping operation to the grid position (2,1)(2, 1). The type BB diagonal flipping operations to the grid positions (1,0)(1, 0) or (3,2)(3, 2) have the same effect.

Given an information of an m×nm \times n grid, write a program to output the minimum number of the diagonal operations to make all the elements in the grid to zeros.

입력

Your program is to read from standard input. The first line of input contains two positive integers mm (1≤m≤1,0001 ≤ m≤1\\,000) and nn (1≤n≤1,0001 ≤ n ≤ 1\\,000) where mm and nn indicate the number of rows and columns of the grid, respectively. The rows of the grid are numbered from 00 to m−1m - 1 and the columns are numbered from 00 to n−1n - 1. In the following mm lines, the ii-th line contains nn numbers, separated by spaces, which are zero or one that correspond to the row i−1i - 1 of the grid.

출력

Your program is to write to standard output. Print exactly one line. The line should contain the minimum number of the diagonal operations to make all the elements of the grid to zeros. If it is not possible to make all the elements of the grid zeros, the program should print the number -1.

예제4

  1. 예제 1

    입력
    4 3
    1 0 1
    0 0 1
    1 1 1
    0 0 0
    
    예상 출력
    4
    
  2. 예제 2

    입력
    2 2
    1 1
    1 1
    
    예상 출력
    2
    
  3. 예제 3

    입력
    3 3
    1 0 1
    0 1 0
    1 0 1
    
    예상 출력
    3
    
  4. 예제 4

    입력
    3 3
    0 0 1
    0 0 1
    1 0 1
    
    예상 출력
    -1