Fix the Pond

Time limit1sMemory limit128 MB

Summary
Given a grid of rotatable barriers in a 2N by 2N+1 pond, find the minimum number of barriers to rotate so a path visits every cell once from top-left to bottom-left.
Level

Hard8 of 10

Topics
Graph, BFS, Shortest path, Implementation
Solved
No attempts yet

Problem

A shrimp farm uses a rectangular pond laid out as a grid of unit square cells, each cell one meter on a side. For a given integer NN, the pond has 2N2N rows and 2N+12N+1 columns. Inside the pond there are exactly (2N−1)×N(2N-1)\times N barriers, each two meters long, used to temporarily divide the pond into smaller sections for breeding different kinds of shrimp.

The middle point of each barrier is fixed at integer coordinates (a,b)(a, b), where 0<a<2N0 < a < 2N and 0<b<2N+10 < b < 2N+1, and aa and bb are either both odd or both even. A barrier can be rotated around its middle point to change the pond configuration, but a rotation only switches it between two positions, both parallel to the sides of the pond: vertical or horizontal.

At the end of every season the pond is emptied for maintenance and cleaning, and must be reconfigured so that a special machine can sweep the pond floor. The machine starts at the top-left cell, must pass through every cell exactly once, and must finish at the bottom-left cell.

Given a pond configuration, write a program that determines the minimum number of barrier switches needed to reconfigure the pond as described above. There is always at least one way to reconfigure the pond as required.

Input

The input consists of several test cases and ends at end of file. Each test case is described using several lines.

The first line contains an integer NN, indicating that the pond has 2N2N rows and 2N+12N+1 columns (1≤N≤3001 \le N \le 300). Each of the next 2N−12N-1 lines contains a string of NN characters describing the orientations of the barriers. In the ii-th line, the jj-th character gives the orientation of the barrier whose middle point is at (i,2j−1)(i, 2j-1) if ii is odd, or at (i,2j)(i, 2j) if ii is even, for i=1,2,…,2N−1i = 1, 2, \ldots, 2N-1 and j=1,2,…,Nj = 1, 2, \ldots, N. The character is the uppercase letter 'V' if the orientation is vertical, or the uppercase letter 'H' if it is horizontal.

Output

For each test case, output a single line with an integer representing the minimum number of barrier switches needed to reconfigure the pond as specified.

Examples3

  1. Example 1

    Input
    3
    HVH
    VVV
    HHH
    HHH
    VHV
    1
    H
    1
    V
    
    Expected output
    4
    0
    1
    
  2. Example 2

    Input
    1
    H
    
    Expected output
    0
    
  3. Example 3

    Input
    1
    V
    
    Expected output
    1