Place exactly 3 walls on empty cells of a small grid to maximize the number of cells the virus cannot reach.
Medium5Brute forceBFSImplementationGraphInterviewNo attempts yetTime limit2sMemory limit512 MBA virus that is lethal to humans leaked inside a laboratory. The virus has not spread yet, so you are going to build walls in the laboratory to stop it.
The laboratory is an N×M rectangle divided into squares of size 1×1. Every square is either an empty cell or a wall, and a wall fills one whole cell.
Some cells hold the virus. The virus spreads to every empty cell next to it, up, down, left, or right. You can build 3 new walls, and you must build all 3 of them.
For example, take a laboratory that looks like this.
2 0 0 0 1 1 0
0 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 0 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0
Here 0 is an empty cell, 1 is a wall, and 2 is a cell that holds the virus. If you build no wall at all, the virus reaches every empty cell.
If you build walls at row 2 column 1, row 1 column 2, and row 4 column 6, the map becomes this.
2 1 0 0 1 1 0
1 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 1 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0
After the virus spreads, the map looks like this.
2 1 0 0 1 1 2
1 0 1 0 1 2 2
0 1 1 0 1 2 2
0 1 0 0 0 1 2
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0
Once the 3 walls are built, the cells the virus cannot reach form the safe area. The safe area of the map above has size 27.
Given the map of the laboratory, write a program that finds the largest safe area you can obtain.
The first line has the height N and the width M of the map. (3≤N,M≤8)
Each of the next N lines has one row of the map. 0 is an empty cell, 1 is a wall, and 2 is a cell that holds the virus. The number of 2s is at least 2 and at most 10.
The map has at least 3 empty cells.
Print the largest size of the safe area on the first line.