title: traverse matrix maze in 8 directions
body: <blockquote>
    <p>You are given a matrix with 1s and 0s, where 0 represents free path and 1 represents blocked area. You can move in any of the 8 directions. Find the shortest path from source to destination.</p>
  </blockquote>
  
  <p>The solution i was able to come up with, where <code>dp[i,j]</code> stores minimum distance from starting vertex: </p>
  
  <pre><code>recursion(int i, int j , int sum)
  {
  
    if(!issafe(i,j) || isvisited[i,j]) // within bounds
    return ;
  
    if(matrix(i,j)==0)//blocked
    return ;
  
    isvisited[i,j]=true;
  
    dp[i,j] = min(dp[i,j] , sum);
    // directions have usual meaning
  
    recursion(east ,sum+1);  // i , j+1
    recursion(north , sum+1);  //i-1 , j
    recursion(west , sum+1);
    recursion(south , sum+1);
    recursion(north-east , sum+1);
    recursion(north-west , sum+1);
    recursion(south-east , sum+1);
    recursion(south-west , sum+1);
  
    isvisited[i,j]=false;
  
  return;
  }  
  </code></pre>
  
  <p>now my doubt is that suppose we can reach [i,j] from 8 positions. As soon as I reach it from position 1, say min. path is x units, I recursively check for its neighbours straight away . Now, I come from path 2 and find that min. path (previously x) is now y not x, and now again recursively check. So, I have done extra calculations at step 1 which are not required. Is there any method by which I recursively check neighbours only after I find the min. path(reachable from all 8 positions) at current cell? </p>