#JavaScript (ES6), <s> 228 ... 184 </s> 182 bytes Expects a matrix of characters as input. <!-- language-all: lang-javascript --> m=>m.map((r,Y)=>r.map((_,X)=>n+=(g=(x,y,z,q=z&2,r=m[y],v=r&&r[x])=>v?(v=r[x]=+v||64+(v>{})+!++v)^(r[x]|=4<<z)?g(x+--q*~z%2,y-q*z%2,z^2)&g(x,y,z^=v&1||3)|!(r[x]=v):1:0)(X,Y,0)),n=0)|n [Try it online!](https://tio.run/##TZDBcoIwEIbveYp4KGZLBLROD47BU/sCXnSMdhgESgeCBsoIYl@dbuDQHrL/v5vv38zkK6iDMtTppZqp4hz1sehz4edOHlwY03wPwtdj88F32ChbsESwG294y6@itRZci/zQHHkttGXpw@2IVL1h2KIXdt11r0ub1f79AfbEtms4MXPTieV63cImYTd7Nrs@/7RPC96gMdqeFmAl4ysnUVvzrnuBbjIERQ2r@coDtuN77gFwJTzoVK@j63eqIzaNyyk4OgrO72kWbRsVMg@cqthWOlUJA6e8ZGnFplJJhWBc6Lcg/GQlFT69E0rDQpVFFjlZkbCYlX84wuYjtAEPjuPoIwCQB/SudCUlklIqCUXvEuK6rpQSBWcoFAGJhERHJJKuEYkUopj4V4hhicmRYdUwNAmzmuI1NQClaAxkzKBjiI5Bg@IhwxxnZCANYyqupL8 "JavaScript (Node.js) – Try It Online")