Detect numbers surrounded by equal numbers in a matrix I need an algorithm that extracts from a matrix those fields that are surrounded by equal values. I'll provide you an example to see it clearer.


*

*This is my intitial matrix.


$$
        \begin{matrix}
        1 & 1 & 1 & 1 & 1 & 0 & 1 \\
        1 & 0 & 1 & 0 & 0 & 0 & 1 \\
        1 & 0 & 1 & 1 & 1 & 0 & 1 \\
        0 & 0 & 1 & 0 & 1 & 0 & 1 \\
        1 & 1 & 1 & 0 & 1 & 1 & 1 \\
        0 & 0 & 1 & 0 & 0 & 0 & 1 \\
        1 & 1 & 1 & 1 & 1 & 1 & 1 \\
        \end{matrix}
$$


*

*As you can see, the spaces marked with an "X" are those fields that
are surrounded by equal values, in this case, surrounded by value 1.


$$
        \begin{matrix}
        1 & 1 & 1 & 1 & 1 &   & 1 \\
        1 &   & 1 &   &   &   & 1 \\
        1 &   & 1 & 1 & 1 &   & 1 \\
          &   & 1 & X & 1 &   & 1 \\
        1 & 1 & 1 & X & 1 & 1 & 1 \\
          &   & 1 & X & X & X & 1 \\
        1 & 1 & 1 & 1 & 1 & 1 & 1 \\
        \end{matrix}
$$
The question is if there exists any mathematic formula that can return which are those fields. If not, I'd be grateful if you gave me some theorems that can help me developing the algorithm.
Thanks.
 A: I’m afraid that no theorems or formulas can help you much in the developing of the algorithm, and therefore  you should concentrate on the algorithm itself. I wrote a simple Pascal program to illustrate one of the simplest of such algorithms. 
program SurNum;
const
  m=7;
  n=7;
  var
    IFi,OFi:Text;
    tC:Char;
    i,j,k:Byte;
    a:array[1..m,1..n]of Byte;
    Found:Boolean;
begin

{matrix input}
assign(IFi,'input.txt');
reset(IFi);
for i:=1 to m do begin
  for j:=1 to n do begin
    read(IFi,tC);
    if tC='1' then a[i,j]:=1 else a[i,j]:=0;
  end;
  readln(IFi);
end;
close(IFi);

{main part}

{find initial unisolated cells}
for j:=1 to n do if a[1,j]=0 then a[1,j]:=2;
for j:=1 to n do if a[m,j]=0 then a[m,j]:=2;
for i:=1 to m do if a[i,1]=0 then a[i,1]:=2;
for i:=1 to m do if a[i,n]=0 then a[i,n]:=2;

{try to find additional unisolated cells}

repeat
Found:=False;
for i:=2 to m-1 do for j:=2 to n-1 do
  if (a[i,j]=0) and ((a[i-1,j]=2) or (a[i+1,j]=2) or (a[i,j-1]=2) or (a[i,j+1]=2)) 
   then begin a[i,j]:=2; Found:=True end;
until not Found;

{matrix output}

assign(OFi,'output.txt');
rewrite(OFi);
for i:=1 to m do begin
  for j:=1 to n do begin
    if a[i,j]=0 then write(OFi,'X');
    if a[i,j]=1 then write(OFi,'1');
    if a[i,j]=2 then write(OFi,' ');
  end;
  writeln(OFi);
end;
close(OFi);

end.

The contents of the file “input.txt” is:
1111101
1010001
1011101
0010101
1110111
0010001
1111111

The contents of the file “output.txt” should be:
11111 1
1 1   1
1 111 1
  1X1 1
111X111
  1XXX1
1111111

