This page is still under construction.

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

Horseshoes

Time limit1sMemory limit128 MB

Summary
On an N x N grid (N at most 5) of parentheses, find the longest walk from the top-left cell, visiting each cell at most once, whose collected characters form a run of '(' followed by an equally long run of ')'.
Level

Medium6 of 10

Topics
DFS, Backtracking, Implementation, Brute force
Solved
No attempts yet

Problem

Bessie the cow finds every balanced-parenthesis string pleasing, but she especially loves strings she calls perfectly balanced: a run of ( characters followed by an equally long run of ) characters. For example:

(((())))

One day, while walking through the barn, Bessie finds an N×NN \times N grid of horseshoes, each oriented so that it looks like either ( or ). Starting from the upper-left corner, she wants to walk around picking up horseshoes so that the string she collects is perfectly balanced. Compute the length of the longest perfectly balanced string she can obtain.

On each step Bessie may move up, down, left, or right. She may only move onto a cell that still contains a horseshoe; when she steps onto it she picks the horseshoe up, so the cell becomes empty and she can never return to it. She always begins by picking up the horseshoe in the upper-left corner. Bessie only keeps a sequence of horseshoes that forms a perfectly balanced string, so she may not be able to pick up every horseshoe in the grid.

Input

  • Line 1: an integer NN (2≤N≤52 \le N \le 5).
  • Lines 2 through N+1N+1: each line is a string of NN parentheses. Together these NN lines describe the N×NN \times N grid.

Output

  • Line 1: the length of the longest perfectly balanced string of horseshoes Bessie can collect. If she cannot collect any balanced string (for example, if the upper-left cell is )), output 0.

Hint

The diagram below shows one grid together with a collection order that yields a perfectly balanced string of length 8. Each digit marks the step at which that cell's horseshoe is picked up; cells that still show a parenthesis are never visited.

1())
2)((
345(
876)

Reading the picked-up horseshoes in step order gives (((()))), which is perfectly balanced and has length 8.

Examples1

  1. Example 1

    Input
    4
    (())
    ()((
    (()(
    ))))
    
    Expected output
    8