Horseshoes
Time limit1sMemory limit128 MB
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 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 ().
- Lines 2 through : each line is a string of parentheses. Together these lines describe the 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
)), output0.
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.