title: How to implement bfs on a matrix?
body: <p>I am having trouble implementing bfs on a matrix. It seems like my code only checks for children of the starting node.</p>
  
  <p>My goal is to find shortest path from 'B' to 'H'. I also think that my code needs a lot of modification. Thank you in advance!           </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstdio&gt;
  #include &lt;queue&gt;
  
  using namespace std;
  
  int bfs(int, int);
  
  bool visited[100][100];
  char matrica[100][100];
  
  int m, n, d;
  
  int main()
  {
  
      scanf("%d %d", &amp;m, &amp;n);
  
      for(int i = 0;i &lt; m;i++){
          for(int j = 0; j &lt; n; j++){
              cin &gt;&gt; matrica[i][j];
              visited[i][j] = false;
          }
      }
  
      for(int i = 0;i &lt; m;i++){
          for(int j = 0; j &lt; n; j++){
              if(matrica[i][j] == 'B'){
                  bfs(i, j);
              }
          }
      }
  
      cout &lt;&lt; endl &lt;&lt; d;
  
      return 0;
  }
  
  int gk[] = {1, 0, -1, 0};
  int gr[] = {0, 1, 0, -1};
  
  int bfs(int x, int y){
  
      cout &lt;&lt; endl;
  
      queue&lt;int&gt;queue_x, queue_y;
      int topx, topy, d=0;
  
      //memset(visited, 0, sizeof visited);
  
      visited[x][y] = true;
  
      queue_x.push(x);
      queue_y.push(y);
  
      while(!queue_x.empty()){
          topx = queue_x.front();
          topy = queue_y.front();
          queue_x.pop();
          queue_y.pop();
  
          if(matrica[topx][topy] == 'H'){
              cout &lt;&lt; endl &lt;&lt; d &lt;&lt; endl;
              d++;
              return d;
          }
  
          for(int i = 0; i &lt; 4; i++){
              x += gk[i];
              y += gr[i];
              if(visited[x][y] == false &amp;&amp; matrica[x][y] != '#'){
                  visited[x][y] = true;
                  matrica[x][y] = '*';
                  queue_x.push(x);
                  queue_y.push(y);
                  d++;
  
                  //-------------
                  for(int i = 0; i &lt; m;i++){
                      for(int j = 0; j &lt; n;j++){
                          cout &lt;&lt; matrica[i][j];
                      }
                      cout &lt;&lt; endl;
                  }
                  //-------------
              }
          }
      }
  }
  </code></pre>
  
  <p>Input/Output:</p>
  
  <p>Input:</p>
  
  <pre><code>5
  5
  #####
  #..B#
  #...#
  #...#
  ###H#
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>#####
  #..B#
  #...#
  #...#
  ###H#
  0
  </code></pre>