Breaking walls

4.3

6 votes
Datastructures, Graphs, Algorithms, Depth First Search
Problem

Bob is assigned a task to collect the maximum stars possible. He has a hammer that can be used to break only one wall!

You are given a grid of size N×M that contains ., , #. Here:

  • . represents all the points where Bob can move
  • # represents the walls and hence bob cannot pass through it or be on it
  • represents the stars bob needs to collect

Note: If you can reach this cell, you can collect this star.

Bob is allowed to start on any of the non # cells and he is free to move up, down, left, or right. But, having the hammer, Bob can break only one wall and move through that broken wall.
Bob wants to collect the maximum possible stars possible. Help Bob by finding the maximum possible stars he can collect.

Input format

  • The first line contains two integers N and M.
  • Next N lines contains M characters consisting of ., , #.

Output format

Print a single line containing a single integer.

Constraints

1N,M1000

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Here Bob can start at (5, 1) and collect all 4 stars at {(5, 1), (5, 2), (4, 1), (4, 2)} and then break the wall at (3, 1) and collect stars at{(2, 1), (1, 1)}
 

Editor Image

?