findPath

Consider a MxN matrix. You are given a start element(index) and an end element. The question is to find a path from start to end. Please note that in some blocks 'X' is marked which means your path cannot go through that element. My solution was to have a tree with 4 nodes (top/left/right/bottom) and recursively check if there is a path from start to end.

notice: remind to mark the node that has been visited.

  1. int M;
  2. int N;
  3. int finished=false;
  4. vector<vector<int> > matrix(3,vector<int>(4,0));
  5. vector<int> path;
  6. vector<vector<int> > flag(3,vector<int>(4,0));
  7. void findPath(vector<int> path, int startx,int starty,int endx,int endy) {
  8. if(flag[startx][starty]==1) return;
  9. path.push_back(startx*N+starty);
  10. flag[startx][starty] = 1;
  11. if(startx==endx && starty==endy) {
  12. finished = true;
  13. for(int i=0;i<path.size();i++) {
  14. cout<<"("<<path[i]/N<<","<<path[i]%N<<")"<<endl;
  15. }
  16. return;
  17. }
  18. if(finished==false && startx+1<M && matrix[startx+1][starty]!=1) findPath(path,startx+1,starty,endx,endy);
  19. if(finished==false && startx-1>0 && matrix[startx-1][starty]!=1) findPath(path,startx-1,starty,endx,endy);
  20. if(finished==false && starty+1<N&&matrix[startx][starty+1]!=1) findPath(path,startx,starty+1,endx,endy);
  21. if(finished==false && starty-1>0&&matrix[startx][starty-1]!=1) findPath(path,startx,starty-1,endx,endy);
  22. path.pop_back();
  23. flag[startx][starty]=0;
  24. }

 

posted @ 2014-09-05 22:30  purejade  阅读(304)  评论(0编辑  收藏  举报