Approach for solving a Breadth first search(BFS) components problem

70 views Asked by At

I am trying to solve this code challenge:

A new king in the North must quickly gather bannermen to defend their realm. Advisers have assessed the map, determining the minimum number of bannermen needed for full defense.

The goal is to minimize the army size while ensuring complete protection. Defense is required only against armies moving horizontally or vertically. The kingdom is considered defended if there's no route to the castle from outside the map without crossing fully defended areas.

Squares labeled 0 represent impassable mountains or walls. The king must plan for the worst-case scenario, assuming inability to hold any position outside the given map.

Input

The input is given in the form of the (rectangular) strategic map which your advisors came up with. Every square in the map is assigned a number of bannermen which would be required to defend the position against any potential army. The map is formatted as follows:

In the first line you are given two integers rows and cols specifying the dimensions of the map. This line is followed by row lines, each containing col integers, the number of bannermen necessary to defend each square. Finally, you are given the position of your own castle on the map.

Output

Output an integer on a single line, the smallest possible army you would require to defend the kingdom given in the input.

Sample Input

7 8
42 42  0  0  0  0  0 16
42 11 14 42 42 42 10 16
42  0 42 42 42 42  0 16
42  0 42 42 42 42  0 42
42  0 42 42 42 42  0 42
42 11 42 42 42  5  5 42
42 42  0  0  0 42 42 42
3 4

Sample output

37

Explanation

The castle can still be defended when armies are removed from all the squares marked with a dash below. The total of remaining battlemen is thus minimized:

 -  -  0  0  0  0  0  -
 - 11  -  -  -  - 10  -
 -  0  -  -  -  -  0  -
 -  0  -  -  -  -  0  -
 -  0  -  -  -  -  0  -
 - 11  -  -  -  5  -  -
 -  -  0  0  0  -  -  -

11 + 10 + 11 + 5 = 37

enter image description here

The approach I have tried till now:

  1. BFS from the castle co-ordinates to outside and as soon as 0 cells are encountered add all the non-zero ones after that level but will it give the minimum cost?

  2. BFS from the outer boundary to inside and break as soon as zero is encountered but I know this is not a correct approach.

How do I find the critical points from where the components containing the castle point is connected with other regions?

0

There are 0 answers