This page is still under construction.

Parts of this page are still being built. What you see may change.

One is Good, but Two is Better

Time limit1sMemory limit128 MB

Summary
Given an N by M grid of 0, 1, and 2, cover every 2 with two rectangles that avoid 1, minimizing the total area covered.
Level

Medium7 of 10

Topics
Brute force, Prefix sum, Matrix, Greedy
Solved
No attempts yet

Problem

You are given an N×MN \times M matrix whose entries are each 00, 11, or 22. At least one entry equals 22.

Choose two axis-aligned rectangles (they may overlap, and they may even be identical) so that:

  • every cell equal to 22 lies inside at least one of the two rectangles, and
  • neither rectangle contains any cell equal to 11 (cells equal to 00 are allowed inside a rectangle).

The area of a rectangle is the number of cells it covers. Among all valid choices, minimize the area of the region covered by the two rectangles together (a cell covered by both rectangles is counted once).

Report that minimum combined area, or report that no valid pair of rectangles exists.

Input

The first line contains two integers NN and MM. Each of the next NN lines contains MM integers, giving the matrix row by row; every value is 00, 11, or 22.

Output

Print a single integer: the minimum combined area of the two rectangles, or −1-1 if no valid pair exists.

Constraints

  • 1≤N,M≤501 \le N, M \le 50
  • Every matrix entry is 00, 11, or 22.
  • At least one entry equals 22.

Examples4

  1. Example 1

    Input
    3 4
    1 2 1 0
    2 0 2 2
    1 2 1 0
    
    Expected output
    6
    
  2. Example 2

    Input
    1 1
    2
    
    Expected output
    1
    
  3. Example 3

    Input
    5 3
    2 1 0
    1 1 1
    0 1 2
    1 1 1
    2 1 0
    
    Expected output
    -1
    
  4. Example 4

    Input
    3 3
    2 0 0
    0 0 0
    0 0 2
    
    Expected output
    2