[Question]
  [
**Background:** Too many illegal immigrants from Blandia are crossing the border to Astan. The emperor of Astan has tasked you with digging a trench to keep them out, and Blandia must pay for the expenses. Since all typists have been furloughed until the trench is arranged, your code must be as short as possible.\*
**Task:** Given a 2D map of the border between Astan and Blandia, make the Blands pay (with land) for a border trench.
**For example:** With Astanian cells marked `A`, Blandic cells marked `B` and trench cells marked `+` (the map frames are only for clarity):
```
┌──────────┐ ┌──────────┐
│AAAAAAAAAA│ │AAAAAAAAAA│
│ABAAAAAABA│ │A+AAAAAA+A│
│ABBBAABABA│ │A+++AA+A+A│
│ABBBAABABA│ │A+B+AA+A+A│
│ABBBBABABA│→│A+B++A+A+A│
│ABBBBABBBB│ │A+BB+A++++│
│ABBBBABBBB│ │A+BB+A+BBB│
│ABBBBBBBBB│ │A+BB+++BBB│
│BBBBBBBBBB│ │++BBBBBBBB│
└──────────┘ └──────────┘
```
**Details:** The map will have at least three rows and three columns. The top row will be entirely Astanian and the bottom row will be entirely Blandic.  
 You may use any three values to represent Astanian territory, Blandic territory, and border trench, as long as input and output are consistent.
**Automaton formulation:** A Blandic cell with at least one Astanian cell in its [Moore neighbourhood](https://en.wikipedia.org/wiki/Moore_neighborhood) becomes a border trench cell.
# Test cases
```
[
  "AAAAAAAAAA",
  "ABAAAAAABA",
  "ABBBAABABA",
  "ABBBAABABA",
  "ABBBBABABA",
  "ABBBBABBBB",
  "ABBBBABBBB",
  "ABBBBBBBBB",
  "BBBBBBBBBB"
]
```
becomes:
```
[
  "AAAAAAAAAA",
  "A+AAAAAA+A",
  "A+++AA+A+A",
  "A+B+AA+A+A",
  "A+B++A+A+A",
  "A+BB+A++++",
  "A+BB+A+BBB",
  "A+BB+++BBB",
  "++BBBBBBBB"
]
```
---
```
[
  "AAA",
  "AAA",
  "BBB"
]
```
becomes:
```
[
  "AAA",
  "AAA",
  "+++"
]
```
---
```
[
  "AAAAAAAAAA",
  "AAAABBBAAA",
  "AAAABBBAAA",
  "AAAABBBAAA",
  "AAAAAAAAAA",
  "BBBBBBABBB",
  "BBBBBBAABB",
  "BBBAAAAABB",
  "BBBBBBBBBB"
]
```
becomes:
```
[
  "AAAAAAAAAA",
  "AAAA+++AAA",
  "AAAA+B+AAA",
  "AAAA+++AAA",
  "AAAAAAAAAA",
  "++++++A+++",
  "BB++++AA+B",
  "BB+AAAAA+B",
  "BB+++++++B"
]
```
---
\* DISCLAIMER: ANY RESEMBLANCE TO ACTUAL GEOPOLITICS IS PURELY COINCIDENTAL!
  
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
2#-#~Erosion~1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n5ioYKsQku@ckViUmFySWuScn5LqUM2loKDkCAdKOmC@E4TnBOc7OYF4@PhOmHwgwMN3QvCdEHyuWl0zUwV9fQXX5Ix8Lq402/9GyrrKda5F@cWZ@Xl1hmr/QRIOaQ6Jif8B "Wolfram Language (Mathematica) – Try It Online")
Or (39 bytes):
```
MorphologicalPerimeter[#,Padding->1]+#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n5ioYKsQku@ckViUmFySWuScn5LqUM2loKDkCAdKOmC@E4TnBOc7OYF4@PhOmHwgwMN3QvCdEHyuWl0zUwV9fQXX5Ix8Lq402/@@@UUFGfk5@elAP@QEpBZl5qYCHR@trBOQmJKSmZeua2cYq62s9h@kwSHNITHxPwA "Wolfram Language (Mathematica) – Try It Online")
What else would we expect from Mathematica? Characters used are `{Astan -> 0, Blandia -> 1, Trench -> 2}`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 8 bytes
*Inspired by [@flawr's Octave answer](https://codegolf.stackexchange.com/a/178820/36398) and [@lirtosiast's Mathematica answer](https://codegolf.stackexchange.com/a/178813/36398).*
```
EG9&3ZI-
```
The input is a matrix with Astan represented by `0` and Blandia by `1`. Trench is represented in the output by `2`.
[Try it online!](https://tio.run/##y00syfn/39XdUs04ylP3//9oAwUMaA0kDFGEDGGChlAJQ6IEDXELgiFBQUOEoCGRgrEA "MATL – Try It Online")
### How it works
```
E       % Implicit input. Multiply by 2, element-wise
G       % Push input again
9       % Push 9
&3ZI    % Erode with neighbourhood of 9 elements (that is, 3×3) 
-       % Subtract, element-wise. Implicit display
```
[Answer]
# JavaScript (ES7), ~~84~~ 82 bytes
*Saved 2 bytes thanks to @Shaggy*
Takes input as a matrix of integers, with \$3\$ for Astan and \$0\$ for Blandia. Returns a matrix with the additional value \$1\$ for the trench.
```
a=>(g=x=>a.map(t=(r,Y)=>r.map((v,X)=>1/x?t|=(x-X)**2+(y-Y)**2<v:v||g(X,y=Y)|t)))()
```
[Try it online!](https://tio.run/##pcrNCoJAFIbhvVcxy3NstKl20bHbUMTFYCqFOqLDoDD3Pv1QEGRBCO/i@@C5SCOHvD93OmjVqXAlOUkRVDRSJMNGdqAJep4gRf3jguHx7WzW41FbgjGI0fe3K5iC5D4OZm@srSDmEyVoNSICuly1g6qLsFYVlJB6jKVsx7/HMv4yYg6IDyPepFhsxD/m2QIj5oz4abwM0V0B "JavaScript (Node.js) – Try It Online")
### Commented
```
a => (                      // a[] = input matrix
  g = x =>                  // g = function taking x (initially undefined)
    a.map(t =               //   initialize t to a non-numeric value
      (r, Y) =>             //   for each row r[] at position Y in a[]:
      r.map((v, X) =>       //     for each value v at position X in r[]:
        1 / x ?             //       if x is defined (this is a recursive call):
          t |=              //         set the flag t if:
            (x - X) ** 2 +  //           the squared Euclidean distance
            (y - Y) ** 2    //           between (x, y) and (X, Y)
            < v             //           is less than v (3 = Astan, 0 = Blandia)
        :                   //       else (this is the initial call to g):
          v ||              //         yield v unchanged if it's equal to 3 (Astan)
          g(X, y = Y)       //         otherwise, do a recursive call with (X, Y) = (x, y)
          | t               //         and yield the flag t (0 = no change, 1 = trench)
      )                     //     end of inner map()
    )                       //   end of outer map()
)()                         // initial call to g
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes
```
{x+x&2{++/'3':0,x,0}/~x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJyVkcEKgzAMhu99CpExlQiV7dYehnkGb2PgLsLYYCAeKqLPvsZqa3XIllM/09DfL5XoFKjjqQPg0TkSWarSrOeD6hlrRHe4tkMtqkDJ8v2UcVndHy+pZCvr5NazQjQ8zBHCCxdcsCKOw9xWyIIg0F1DaBmRaI9xy7p2GB2j40R/+BIIDIFlACLHuGHwWV/QQ+CxC0QMjsfjFCiZFU1X54OXdtWjh9yg/yvklfT9wct5EytfuaMZy2Z3P7slr6RzyQi7/eU8jJVbt6NJ2oYNYJa3YFPk9gOnB4/l)
uses `0 1 2` for `"AB+"`
`{` `}` function with argument `x`
`~` logical not
`2{` `}/` twice do
* `0,x,0` surround with 0-s (top and bottom of the matrix)
* `3':` triples of consecutive rows
* `+/'` sum each
* `+` transpose
`x&` logical and of `x` with
`x+` add `x` to
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes[SBCS](https://github.com/abrudz/sbcs)
```
⊢⌈{2∊⍵}⌺3 3
```
this is based on @dzaima's 12-byte solution [in chat](https://chat.stackexchange.com/transcript/message/48516148#48516148). credit to @Adám himself for thinking of using `∊` in the dfn, and to @H.PWiz for reminding us to use the same encoding for input and output
[Try it online!](https://tio.run/##jZGxTgMxDIb3e4rbPFgIRDe2@Bn6ApHooYqTDlVdUNUJVB1HD8GAxAoTO2LpyKP4RQ47TtNrdRV4SPzFduz88TflyeWtL6urjp9epxWvns@6QlZuPnhdL865brj9XvJ6M8pHXTeX0EIO@OF9Jm7B7eYCqmvgx3so/LQEOZDwbJmNQ2ZzNz8FQgdcv3H79fOpl2WZ1w6rF3DJIAdH5pIBkbrDQAcgNggUgXaQTQZ7o7logKhuBNoH7IGEJBd3EHsrYISwx97j3OeTvedrdlgPZ0sBvX@gsDe7aqYC/Q2pxgZyfXU01cB@4X@6qWaqVgLCI5FUg8Gc6RaEUoGtnX3DFsy2uv0C "APL (Dyalog Unicode) – Try It Online")
represents `'AB+'` as `2 0 1` respectively
`{` `}⌺3 3` apply a function to each overlapping 3×3 region of the input, including regions extending 1 unit outside the matrix, padded with 0s
`2∊⍵` is a 2 present in the argument? return a 0/1 boolean
`⊢⌈` per-element max of that and the original matrix
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 220 bytes
It's not as small as the other submissions, but I thought I'd add it for reference.
[FORE!]
```
function m($i,$m){($i-1)..($i+1)|?{$_-in0..$m}}
$h=$a.count-1;$w=$a[0].length-1
foreach($i in 0..$h){-join$(foreach($j in 0..$w){if ($a[$i][$j]-eq'B'-and($a[(m $i $h)]|?{$_[(m $j $w)]-match'A'})){'+'}else{$a[$i][$j]}})} 
```
[Try it online!](https://tio.run/##pVNNj5swED0vv2KELIHlNdp0j9GqiStVaqXu9tBbhCrKOgso2Ck4zYHw21OPCR/Zj6ZVfQC/55nx8xt7q/eyqjO52RyJkbWp4Q4WoQd2LBq4uk9KaZnga1LXMAu8q08KA3xv5UL85TD86xMjOiwmjBCILzHiNcaOC4yYMmJkvNjzF@Doh50ZVT/X7C9Zh9iAGUM0YvECs3NsA2wSO8O9qg6zEbvpRKOT2Hq952eWvwvmr3k@GDBOLx35pKWfoNqLu98Gc/iblmO7saP/zJzX6UxZvmgnZk6Y7nr9X8ux3djlKRbsj@vTfObGcmi5azBeEjHg7kqJ6TpegnPTqbfWlUzSDEIg3@zzg1x1kxooNC6MJPYg7m1GdvEAqVa/ZGU@Vrrkn2utuiC9M1t3ZBLCcb1Tqcm1gjIk@TUpaWP/fEajyP7ZjB7eN@Q7z9VNFJGybT2S3ZEkSvVOGT6bk71Fq5s42kj1ZDI@60XaZNSHWRlteKFzRcJhrejX9rTJ1xDaGiSPV6SIufwZiIAn6hHJsARbx1aInQyHC7BZMS8Tk2bBMmgpbQIWtHJTy2as07a0hSMel44@GM0LdMHZgPvCB11uk0ryhx@FTM1gTWehBYOz7oNjX@VG8kxb//17beAL6rBOuk5E@CSoPwT39Q6ntH1SqVw9wamn@EXdpz2ely/fKt167fH4Gw "PowerShell – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~37 31~~ 26 bytes
This function performs a [morphological erosion](https://en.wikipedia.org/wiki/Erosion_(morphology)) on the Astan (`1-b`) part of the "image" using ~~`conv2`~~ `imerode`, and then uses some arithmetic to make all three areas different symbols. Thanks @LuisMendo for -5 bytes!
```
@(b)2*b-imerode(b,ones(3))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9kG22ggAmtuQwUDFFEDOGihlAZQyJFDfGIQiBhUUMkUUOiRWOt/ztoJGkaaSXpZuamFuWnpGok6eTnpRZrGGtq/k/MKwZK/gcA "Octave – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
>.3 3(2 e.,);._3(0|:@,|.)^:4
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7fSMFYw1jBRS9XQ0rfXijTUMaqwcdGr0NOOsTP5rcilwpSZn5CukKVgqGBooqCgYYYUGWHgGYAjjExIzwClGDAs/hHkB6FE0H4Dl/wMA "J – Try It Online")
`'AB+'` -> `2 0 1`
Inspired by ngn's APL solution. 12 bytes just to pad the matrix with zeroes...
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
≔⪫θ⸿θＰθＦθ⎇∧№ＫＭA⁼Bι+ι
```
[Try it online!](https://tio.run/##fcyxCoMwEAbg3acImU6aPoGTV7oUBIdu1iHYtA0NiTm10KdPEwUdCt70fz93170kdU6aEMph0E8LF6cteMH4jXgumM@LrJrMqHvSdoTEhyMWA6vn5qrISvpCae9wclNsaqXelXOkIN7zMn05@0maAThywXSe6sOSihCaJmNxbR0uZuMiXI2YtGf8d5wd42bcnLVtOH7MDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫θ⸿θ
```
Join the input array with carriage returns rather than the usual newlines. This is needed so that the characters can be printed individually.
```
Ｐθ
```
Print the input string without moving the cursor.
```
Ｆθ
```
Loop over each character of the input string.
```
⎇∧№ＫＭA⁼Bι
```
If the Moore neighbourhood contains an `A`, and the current character is a `B`...
```
+
```
... then overwrite the `B` with a `+`...
```
ι
```
... otherwise print the current character (or move to the next line if the current character is a carriage return).
[Answer]
# JavaScript, 85 bytes
Threw this together late last night and forgot about it. Probably still room for some improvement somewhere.
Input and output is as an array of digit arrays, using `3` for Astan, `0` for Blandia & `1` for the trench.
```
a=>a.map((x,i)=>x.map((y,j)=>o.map(v=>o.map(h=>y|=1&(a[i+v]||x)[j+h]))|y),o=[-1,0,1])
```
[Try it online](https://tio.run/##jZBbDoMgEEX/XYYfDRMpqQvARLZBSSVWq6YVUxqDiXu3KD76SJPOz9xzGTIXKtlKnd7L5rGv1TkbcjpIGklykw1CBpdAI@Ogw5UFNUG7iIJGXU/DHZK8DFrR9wZ4FRQCoO8AK8r3IT7gUMCQqlqra0au6oK4xz0/XsvHlpjTbCbGRv2L2CfZ@kFsIbaRJ7ALME259ua/BhtDjfv/ou2eWxW/LR@nZ3KP/Q7mielfDY1yZBbJCSFmPdBEZ/KeFsiArcVdhzU3AkilyjpJ5n6sE6xpwoJTvFnWhOEJ) (For convenience, maps from & back to the I/O format used in the challenge)
[Answer]
# Javascript, ~~126~~ 118 bytes
```
_=>_.map(x=>x.replace(/(?<=A)B|B(?=A)/g,0)).map((x,i,a)=>[...x].map((v,j)=>v>'A'&&(a[i-1][j]<v|(a[i+1]||x)[j]<v)?0:v))
```
Pass in one of the string arrays from the question, and you'll get an array of ~~strings~~ character arrays (thanks @Shaggy!) out using 0 for the trench. Can *probably* be golfed more (without switching over to numerical arrays), but I can't think of anything at the moment.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~92~~ 80 bytes
```
(?<=¶(.)*)B(?=.*¶(?<-1>.)*(?(1)_)A|(?<=¶(?(1)_)(?<-1>.)*A.*¶.*))
a
iT`Ba`+`.?a.?
```
[Try it online!](https://tio.run/##K0otycxL/P9fw97G9tA2DT1NLU0nDXtbPS0gx95G19AOKKJhr2GoGa/pWANVBOHCpR1BivW0NDW5ErkyQxKcEhO0E/TsE/Xs//93hAMuRycIwwnEdHICMTCZTihMIMBgggEXnOUEAA "Retina 0.8.2 – Try It Online") Loosely based on my answer to [Will I make it out in time?](https://codegolf.stackexchange.com/questions/138108/) Explanation: Any `B`s immediately above or below `A`s are turned into `a`s. This then reduces the problem to checking `B`s to the left or right of `A`s or `a`s. The `a`s themselves also need to get turned into `+`s of course, but fortunately the `i` flag to `T` only affects the regex match, not the actual transliteration, so the `A`s remain unaffected.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
_2FIн¸.øVgN+FYN._3£})εøO}ø}*Ā+
```
Matrices aren't really 05AB1E's strong suit (nor are they my strong suit).. Can definitely be golfed some more, though.  
Inspired by [*@ngn*'s K (ngn/k) answer](https://codegolf.stackexchange.com/a/178814/52210), so also uses I/O of a 2D integer matrix with `012` for `AB+` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f8/3sjN88LeQzv0Du8IS/fTdov004s3PrS4VvNR05rDO/wP76jVOtKg/d/r0O7/0dEGOhgwVgcoaogiZggXNYTKGBIpaohHFAyJEDVEEjXEIhoLAA). (The footer in the TIO is to pretty-print the output. Feel free to remove it to see the matrix output.)
**Explanation:**
```
_                # Inverse the values of the (implicit) input-matrix (0→1 and 1→0)
                 #  i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]]
                 #   → [[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0]]
 2F              # Loop `n` 2 times in the range [0, 2):
   Iн            #  Take the input-matrix, and only leave the first inner list of 0s
                 #   i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] → [0,0,0,0]
     ¸           #  Wrap it into a list
                 #   i.e. [0,0,0,0] → [[0,0,0,0]]
      .ø         #  Surround the inverted input with the list of 0s
                 #   i.e. [[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0]] and [0,0,0,0]
                 #    → [[0,0,0,0],[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0]]
        V        #  Pop and store it in variable `Y`
   g             #  Take the length of the (implicit) input-matrix
                 #   i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] → 4
    N+           #  Add `n` to it
                 #   i.e. 4 and n=0 → 4
                 #   i.e. 4 and n=1 → 5
      F          #  Inner loop `N` in the range [0, length+`n`):
       Y         #   Push matrix `Y`
        N._      #   Rotate it `N` times towards the left
                 #    i.e. [[0,0,0,0],[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0]] and N=2
                 #     → [[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,1,1,1]]
            3£   #   And only leave the first three inner lists
                 #    i.e. [[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,1,1,1]]
                 #     → [[1,0,1,1],[1,0,0,0],[0,0,0,0]]
              }  #  After the inner loop:
    )            #  Wrap everything on the stack into a list
                 #   → [[[0,0,0,0],[1,1,1,1],[1,0,1,1]],[[1,1,1,1],[1,0,1,1],[1,0,0,0]],[[1,0,1,1],[1,0,0,0],[0,0,0,0]],[[1,0,0,0],[0,0,0,0],[0,0,0,0]]]
     €ø          #  Zip/transpose (swapping rows/columns) each matrix in the list
                 #   → [[[0,1,1],[0,1,0],[0,1,1],[0,1,1]],[[1,1,1],[1,0,0],[1,1,0],[1,1,0]],[[1,1,0],[0,0,0],[1,0,0],[1,0,0]],[[1,0,0],[0,0,0],[0,0,0],[0,0,0]]]
       O         #  And take the sum of each inner list
                 #   → [[2,1,2,2],[3,1,2,2],[2,0,1,1],[1,0,0,0]]
        ø        #  Zip/transpose; swapping rows/columns the entire matrix again
                 #   i.e. [[2,1,2,2],[3,1,2,2],[2,0,1,1],[1,0,0,0]]
                 #    → [[2,3,2,1],[1,1,0,0],[2,2,1,0],[2,2,1,0]]
               } # After the outer loop:
                 #   i.e. [[3,5,5,4,2],[4,6,5,4,2],[2,3,2,2,1],[1,1,0,0,0]]
  *              # Multiple each value with the input-matrix at the same positions,
                 # which implicitly removes the trailing values
                 #  i.e. [[3,5,5,4,2],[4,6,5,4,2],[2,3,2,2,1],[1,1,0,0,0]]
                 #   and [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]]
                 #    → [[0,0,0,0],[0,1,0,0],[0,2,1,0],[2,2,1,0]]
   Ā             # Truthify each value (0 remains 0; everything else becomes 1)
                 #  i.e. [[0,0,0,0],[0,1,0,0],[0,2,1,0],[2,2,1,0]]
                 #   → [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,0,0]]
    +            # Then add each value with the input-matrix at the same positions
                 #  i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,0,0]]
                 #   and [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]]
                 #    → [[0,0,0,0],[0,2,0,0],[0,2,2,2],[2,2,1,1]]
                 # (and output the result implicitly)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 187 bytes
```
a=>a.Select((b,i)=>b.Select((c,j)=>{int k=0;for(int x=Math.Max(0,i-1);x<Math.Min(i+2,a.Count);x++)for(int y=Math.Max(0,j-1);y<Math.Min(j+2,a[0].Count);)k+=a[x][y++];return k>1&c<1?9:c;}))
```
Instead of chaining `Take()`s, `Skip()`s, and `Select()`s, instead this uses double for loops to find neighbors. HUGE byte decrease, from 392 bytes to 187. Linq isn't always the shortest!
[Try it online!](https://tio.run/##jZFNb4IwGMfvfIqellaqAreNlx2WLVkipx12IB5q18UHXFmwOAzhs7NWBHXqtj5J6fPyJ//@ytdjvobWQno9lZIHM1irbgOpoog@P8ryQxRssRLB8XnXjdBnjsKWhRGbvIiV4ArjBQUSRosh5zTVea3nURY6/nteYHOuwpip5SRmFXYojF3iV0FXAYnB9iibPOSlVLpu26RXbY9VqVFtD6rUqBJn3gtJZocsqebJ1rbnfiFUWUiURe4ND9z72zvuN4S0vqX/LRhf4g0rUIZA6jthKb7QDxL1UDNp7dF9NPS04dAuzhqeKZrWNYXTaEO19VqAEjOQApNTcwDGXdaPYAA90OiYjkabHN5QjE89I0aRoQbdJyVWbV3lT8/Z/vUiv8I/XGN4g53d@B9wnUuYvEtQ99yoS7Xf0bT9Bg "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Perl 5, ~~58~~ 46 bytes
```
$m=($n=/$/m+"@+")-2;s/A(|.{$m,$n})\KB|B(?=(?1)A)/+/s&&redo
```
[TIO](https://tio.run/##K0gtyjH9/18l11ZDJc9WX0U/V1vJQVtJU9fIuljfUaNGr1olV0clr1YzxtupxknD3lbD3lDTUVNfW79YTa0oNSX//39HOOBydIIwnEBMJycQA5PphMIEAgwmGHA5IZhcYMOBGMaBWwiyDGQ6PiZULcQsR4TRIEVcEHUwJszCf/kFJZn5ecX/dQsMDAA)
-12 bytes thanks to @Grimy
```
/.
/;s/A(|.{@{-}}.?.?)\KB|B(?=(?1)A)/+/s&&redo
```
[TIO](https://tio.run/##K0gtyjH9/19fj0vfuljfUaNGr9qhWre2Vs9ez14zxtupxknD3lbD3lDTUVNfW79YTa0oNSX//39HOOBydIIwnEBMJycQA5PphMIEAgwmGHA5IZhcYMOBGMaBWwiyDGQ6PiZULcQsR4TRIEVcEHUwJszCf/kFJZn5ecX/dQsMDAA)
* `-p` like `-n` but print also
* `-00` paragraph mode
* to get the width-1 `/.\n/` matches the last character of first line
* `@{-}` special array the position of start of match of previous matched groups, coerced as string (first element)
* `s/../+/s&&redo` replace match by `+` while matches
	+ `/s` flag, so that `.` matches also newline character
* `A(|.{@{-}}.?.?)\KB` matches
	+ `AB` or `A` followed by (width-1) to (width+1) characters folowed by `B`
	+ `\K` to keep the left of `B` unchanged
* `B(?=(?1)A)`,
	+ `(?1)` dirverting recursive, to reference previous expression `(|.{$m,$o})`
	+ `(?=..)` lookahead, to match without consuming input
[Answer]
# Java 8, ~~169~~ 145 bytes
```
m->{for(int i=m.length,j,k;i-->0;)for(j=m[i].length;j-->0;)for(k=9;m[i][j]==1&k-->0;)try{m[i][j]=m[i+k/3-1][j+k%3-1]<1?2:1;}catch(Exception e){}}
```
-24 bytes thanks to *@OlivierGrégoire*.
Uses `0` instead of `A` and `1` instead of `B`, with the input being a 2D integer-matrix. Modifies the input-matrix instead of returning a new one to save bytes.
The cells are checked the same as in [my answer for the *All the single eights* challenge](https://codegolf.stackexchange.com/a/175766/52210).
[Try it online.](https://tio.run/##rZNNb4MwDIbv/RW@bAIVWLOdVkanHXZcLz0iDhmlbfgICEy3CvHbWQJBpR9b12mKBNhP4tgvdki31AyXUePHtCjgjTJejQAYxyBfUT@AuTQBtilbgq8Jv@u5HiS6Ldz1SDwKpMh8mAMHp0nMWbVKc7kPmJNYccDXuDFCI7KZac4mti5p6CQu8xS0wz2InEdbIjf0HIfcRh3BfFf1XvEeR3cPJhHWOLqRH0/k@X5K7Nqn6G@0108/yJClHAK9quvGljlm5XssclSptrUkolJtgTnja1EP1bsyMShQ48EHqEI7L0A1MU5WbewhOUDkGBK1gfwJksuwXVdDcgrJGVi3P/uSOMMLDsxrgnyvcK9sr9a/wrN3DkWY/KSTCn8Mh/3wK4WH49T2aKtVP3KMZyWqNuWWHEVpd6LK2dnSHOi086q7FrsCg8RKS7Qy0egYcy0U826VyGLrJc/prrAw7YZAo7oKduaUSq9uvgA)
**Explanation:**
```
m->{                            // Method with integer-matrix parameter and no return-type
  for(int i=m.length,j,k;i-->0;)//  Loop over the rows
    for(j=m[i].length;j-->0;)   //   Inner loop over the columns
      for(k=9;m[i][j]==1&       //    If the current cell contains a 1:
          k-->0;)               //     Inner loop `k` in the range (9, 0]:
        try{m[i][j]=            //      Set the current cell to:
             m[i+k/3-1]         //       If `k` is 0, 1, or 2: Look at the previous row
                                //       Else-if `k` is 6, 7, or 8: Look at the next row
                                //       Else (`k` is 3, 4, or 5): Look at the current row
              [j+k%3-1]         //       If `k` is 0, 3, or 6: Look at the previous column
                                //       Else-if `k` is 2, 5, or 8: Look at the next column
                                //       Else (`k` is 1, 4, or 7): Look at the current column
               <1?              //       And if this cell contains a 0:
                  2             //        Change the current cell from a 1 to a 2
                 :              //       Else:
                  1;            //        Leave it a 1
        }catch(Exception e){}}  //      Catch and ignore ArrayIndexOutOfBoundsExceptions
                                //      (try-catch saves bytes in comparison to if-checks)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~86~~ 80 bytes
```
$p="(.?.?.{$(($args|% i*f '
')-1)})?"
$args-replace"(?s)(?<=A$p)B|B(?=$p`A)",'+'
```
[Try it online!](https://tio.run/##fZLhToMwFIX/9yluWCetBRP/S4C@iJKtcyQMKmVRAzw79raDbU53ScmXw2kvp7m6@VSt2auqmugOEugnqpOAPaX26SljtGjfzbCG8nEHIQl5/MxHngbE6XGrdFVsVMBSw1n6kuRUczlIliZUv@U8iEIRTiMhGSMRywKSL0Vy6UEiSolwi/IKbd2gKyLPGGTRr0bCg0AUAsGhvESxoJWtS8zoGiEKh@49N@JLKLeuuruF51zall/C3Bj0Hp68vlt@Tokm4n0z/p8dc2PmE0rxh3ryClf4gbi4eD14ur8@j758dg4DrKEnYIseCh1R9aXVplNbO0b01eutMseqs8KDnS50Xcqx@lj2OH01@1dwrDfN4aDqDrp9aaAqawVdA9vS2In7Bu8zZJx@AA "PowerShell – Try It Online")
The map is a string with newlines. This script replaces `B` to `+` with regexp `(?<=A(.?.?.{$MapWidth-1})?)B|B(?=(.?.?.{$MapWidth-1})?A)`.
Less golfed Test script:
```
$f = {
$l=($args|% indexOf "`n")-1
$p="(.?.?.{$l})?"
$args-replace"(?s)(?<=A$p)B|B(?=$p`A)",'+'
}
@(
,(@"
AAAAAAAAAA
ABAAAAAABA
ABBBAABABA
ABBBAABABA
ABBBBABABA
ABBBBABBBB
ABBBBABBBB
ABBBBBBBBB
BBBBBBBBBB
"@,@"
AAAAAAAAAA
A+AAAAAA+A
A+++AA+A+A
A+B+AA+A+A
A+B++A+A+A
A+BB+A++++
A+BB+A+BBB
A+BB+++BBB
++BBBBBBBB
"@)
,(@"
AAA
AAA
BBB
"@,@"
AAA
AAA
+++
"@)
,(@"
AAAAAAAAAA
AAAABBBAAA
AAAABBBAAA
AAAABBBAAA
AAAAAAAAAA
BBBBBBABBB
BBBBBBAABB
BBBAAAAABB
BBBBBBBBBB
"@,@"
AAAAAAAAAA
AAAA+++AAA
AAAA+B+AAA
AAAA+++AAA
AAAAAAAAAA
++++++A+++
BB++++AA+B
BB+AAAAA+B
BB+++++++B
"@)
) | % {
    $map,$expected = $_
    $result = &$f $map
    $result-eq$expected
    #$result # uncomment this line to display results
}
```
Output:
```
True
True
True
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 102 bytes
```
->a{a+=?.*s=a.size
(s*9).times{|i|a[j=i/9]>?A&&a[j-1+i%3+~a.index($/)*(i/3%3-1)]==?A&&a[j]=?+}
a[0,s]}
```
[Try it online!](https://tio.run/##fY7RCoIwGIXv/6eISFGXM/HKiynba8guFiksKKIpVGqvvpyaJVIHBt/PDpzvWu3vuiDaT0QtEEmxp4jASj5ycJQXu7iUp1zVjWxEdiQyiHmSUtvuDj9E0orQU2B5PuQ3ZxO4niODyIr80OWEjDVOUtSCyHZbxVsNl6pUqyKDNZ0ClA3ADDJmYIlshl0W2AcmYmvg0O/BbBXM@/09SRkhY/APx@6wRz/zpgRD743fUgD6BQ "Ruby – Try It Online")
input/output as a newline separated string
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ 119 bytes
```
lambda m:[[[c,'+'][c=='B'and'A'in`[x[j-(j>0):j+2]for x in m[i-(i>0):i+2]]`]for j,c in e(l)]for i,l in e(m)];e=enumerate
```
[Try it online!](https://tio.run/##lZDNisMgFIX3PoV0o1Jbhi5TUoiLvoQj1EkMcyWakKbQefpU40z6S2Huyu@ccy8Hu5/hu/Wbsc4/x0a7r0pjl0kpS06WRMkyz4kg2lekIOAP8iztitrdB8vscqPqtsdnDB47CSsKUYYgq8PkWF5Gz9CGTQy8SeyY2prc@JMzvR7MWJka74OaIRxzU6qmTne0gePAHYsO7nrwAyZkbVvw4SZKCkJ7KoO9KOZZ8IlFIjGzEJHesXjmMG9YXFlcGSl2W@s3//d4kbgvHkvHbv/g2/1UongoFndmTh/zuvh4AQ "Python 2 – Try It Online")
I/O is a list of lists
[Answer]
# TSQL, 252 bytes
Splitting the string is very costly, if the string was split and already in a table the byte count would be 127 characters. Script included in the bottom and completely different. Sorry for taking up this much space.
Golfed:
```
WITH C as(SELECT x,x/z r,x%z c,substring(@,x+1,1)v
FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
WHERE'P'=type)SELECT @=stuff(@,x+1,1,'+')FROM c WHERE
exists(SELECT*FROM c d WHERE abs(r-c.r)<2and
abs(c-c.c)<2and'AB'=v+c.v)PRINT @
```
Ungolfed:
```
DECLARE @ varchar(max)=
'AAAAAAAAAA
ABAAAAAABA
ABBBAABABA
ABBBAABABA
ABBBBABABA
ABBBBABBBB
ABBBBABBBB
ABBBBBBBBB
BBBBBBBBBB';
WITH C as
(
  SELECT x,x/z r,x%z c,substring(@,x+1,1)v
  FROM spt_values
  CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
  WHERE'P'=type
)
SELECT
  @=stuff(@,x+1,1,'+')
FROM c
WHERE exists(SELECT*FROM c d 
         WHERE abs(r-c.r)<2 
           and abs(c-c.c)<2 and'AB'=v+c.v)
PRINT @
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/968018/dig-a-border-trench)**
# TSQL, 127 bytes(Using table variable as input)
Execute this script in management studio - use "query"-"result to text" to make it readable
```
--populate table variable
USE master
DECLARE @v varchar(max)=
'AAAAAAAAAA
ABAAAAAABA
ABBBAABABA
ABBBAABABA
ABBBBABABA
ABBBBABBBB
ABBBBABBBB
ABBBBBBBBB
BBBBBBBBBB'
DECLARE @ table(x int, r int, c int, v char)
INSERT @
SELECT x+1,x/z,x%z,substring(@v,x+1,1)
FROM spt_values
CROSS APPLY(SELECT number x,charindex(char(10),@v)z)z
WHERE'P'=type and len(@v)>number
-- query(127 characters)
SELECT string_agg(v,'')FROM(SELECT
iif(exists(SELECT*FROM @
WHERE abs(r-c.r)<2and abs(c-c.c)<2and'AB'=v+c.v),'+',v)v
FROM @ c)z
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/968103/dig-a-border-trench)** - warning output is selected and not readable. Would be readable with print, but that is not possible using this method
]