title: Hexagon map finding if some grids are surrounded algorithm
body: <p>I am creating a simple math game in hexagon geometry through Unity. It is not about Unity indeed.</p>
  
  <p>I borrow the <a href="https://i.stack.imgur.com/Do9zi.png" rel="nofollow noreferrer">Image</a> from <a href="https://catlikecoding.com/unity/tutorials/" rel="nofollow noreferrer">https://catlikecoding.com/unity/tutorials/</a>, to illustrate the problem, it is quite huge so I put it in the link.</p>
  
  <hr>
  
  <p><strong>Background</strong></p>
  
  <p>Same as tutorial in the link provided, I use an array for saving data, to simplify it, it is like:</p>
  
  <pre><code>[      0, 0, 0, 0,    
          0, 0, 0, 0,
         0, 0, 0, 0,
          0, 0, 0, 0,
         0, 0, 0, 0      ]
  </code></pre>
  
  <p>My aim is</p>
  
  <blockquote>
    <p>Check if one or more than one grids are surrounded by another type of grid.</p>
  </blockquote>
  
  <p>Definition</p>
  
  <blockquote>
    <p><strong>Surrounded</strong> means for a grid or group of connected grid, all neighbors are in different flag of them.</p>
  </blockquote>
  
  <p>For example,</p>
  
  <pre><code>[      0, 1, 1, 0,    
          1, 0, 1, 0,
         0, 1, 1, 0,
          0, 0, 0, 0,
         0, 0, 0, 0       ]
  
  //Should become
  
  [      0, 1, 1, 0,    
          1, 1, 1, 0,
         0, 1, 1, 0,
          0, 0, 0, 0,
         0, 0, 0, 0       ]
  </code></pre>
  
  <p>It is pretty easy for this case I don't even need an algorithm, as I can create the grid with reference of its neighbor, like</p>
  
  <pre><code>class grid{
      grid[] neighbor;
      int flag; //0 or 1
  }
  </code></pre>
  
  <p>So, when I need to check if a grid is surrounded, I just need to loop its <code>neighbor</code>.</p>
  
  <hr>
  
  <p><strong>Problem</strong></p>
  
  <p>However, this method become tedious in the following case</p>
  
  <pre><code>[      0, 1, 1, 1,     
          1, 0, 0, 1,
         0, 1, 1, 1,
          0, 0, 0, 0,
         0, 0, 0, 0       ]
  </code></pre>
  
  <p>So, I also need to check its neighbor's neighbor now, like</p>
  
  <pre><code>foreach (grid i in neighbor){
     bool is_surrounded = false;
     if (grid.flag == 1) {
         //Good
     } else {
         //Check its neighbor, if every neighbor except i is 1, then return True. 
     }
  }
  </code></pre>
  
  <p>It is working fine for 2, but what if there is 3 blank grids. Recursion is not ok, as when a grid is not surrounded like</p>
  
  <pre><code>[      0, 1, 1, 1,     
          1, 0, 0, 1,
         0, 1, 0, 1,
          0, 0, 0, 0,
         0, 0, 0, 0       ]
  </code></pre>
  
  <p>I will then loop the whole map for checking around 8^n times.</p>
  
  <hr>
  
  <p><strong>Question</strong></p>
  
  <p>I think there is cleverer method I didn't realize, I welcome any kind/language of answer or even just an idea. For sure, I will bounty for working ans with explanation.</p>
  
  <p>Thanks.</p>