Inspired by this, this and this.

So, now that the evil farmer has set your field on fire, you naturally want to put it out. You have a bunch of friends who all have buckets, and you want a program to figure out where to place everyone to save as much of your wheat as possible.

Your Task:

Write a program or function that takes as arguments the field, and the number of friends with buckets you have, and outputs the field with the optimal placement of friends with buckets. The field will be represented by either a string, an array of strings, an array of arrays of characters, or any other method you deem appropriate. The field consists of numbers representing how intense the fire is. A 0 indicates that an area is not on fire. 1-4 represents the fire growing in intensity. When the fire reaches stage 4, it spreads fires to all directly (not diagonally) adjacent areas that are not adjacent (directly or diagonally) to a bucket brigadier. After stage 4, the fire dies, and becomes an "A", representing ashes. In your output, friends with buckets are represented by a B. They may be placed anywhere that does not contain flames. When a friend is placed, any flames adjacent to them go out.


An integer representing the number of friends with buckets available, and an array or string representing the field.


The field, with friends placed to optimise the amount of wheat saved. If you use a different set of characters than mentioned above, please include that information in your answer.

Test Cases:

1, 1001         10B0
   000000000 -> 000000000
      000000       000000

2, 1000000000010000101       100000000001B000101   Note that the friend on the second line could be placed in many other locations.  
   00000000000000         -> 0000B000000000
                00000000                  00000000
                00000000                  00000000


This is , shortest solution in bytes wins!