Under construction

Still being built. Things may change

Gomgomi's Diet Management 2

Time limit3.5sMemory limit1024 MB

Summary
Given a grid with obstacles, find the fewest new obstacles that cut every path from the top-left cell to the bottom-right cell.
Level

Medium6 of 10

Topics
Graph, BFS
Solved
No attempts yet

Problem

Gomgomi walking toward the chicken

The grid has NN rows and MM columns, and a delicious chicken is placed at cell (N,M)(N,M). Gomgomi starts at (1,1)(1,1) and wants to reach the chicken. Gomgomi can move up, down, left, and right freely, but cannot step onto a cell with an obstacle or leave the grid.

Chungchung blocking Gomgomi from reaching the chicken

Chungchung, Gomgomi's health trainer, decides to stop Gomgomi from reaching the chicken. Chungchung can place a new obstacle on any cell that currently has no obstacle to block the path. If some cells already have obstacles, Chungchung may be able to place fewer new ones.

Given the state of the grid, print the minimum number of additional obstacles Chungchung must place to block Gomgomi from reaching the chicken. Obstacles cannot be placed on (1,1)(1, 1) or (N,M)(N, M).

Input

The first line contains integers NN and MM separated by a space. (1≤N,M≤2 0001 \le N, M \le 2\ 000, 3≤N×M3 \le N \times M)

From the second line onward, the next NN lines give the state of the grid. 00 means a cell that can be passed through, and 11 means a cell with an obstacle that cannot be passed through.

It is guaranteed that (1,1)(1,1) and (N,M)(N,M) have no obstacles.

Output

Print the minimum number of additional obstacles Chungchung must place to block Gomgomi's movement.

Examples3

  1. Example 1

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

    Input
    3 3
    0 1 1
    1 1 1
    1 1 0
    
    Expected output
    0
    
  3. Example 3

    Input
    9 10
    0 0 1 0 0 0 0 0 0 0
    0 0 1 0 0 0 0 0 0 0
    0 0 1 0 0 0 0 1 0 0
    0 0 1 0 0 0 1 1 0 0
    0 0 1 0 0 0 0 1 0 0
    0 0 1 1 0 0 0 1 0 0
    0 0 1 0 0 0 0 1 0 0
    0 0 0 0 0 0 0 1 0 0
    0 0 0 0 0 0 0 1 0 0
    
    Expected output
    2