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.
- int M;
- int N;
- int finished=false;
- vector<vector<int> > matrix(3,vector<int>(4,0));
- vector<int> path;
- vector<vector<int> > flag(3,vector<int>(4,0));
- void findPath(vector<int> path, int startx,int starty,int endx,int endy) {
- if(flag[startx][starty]==1) return;
- path.push_back(startx*N+starty);
- flag[startx][starty] = 1;
- if(startx==endx && starty==endy) {
- finished = true;
- for(int i=0;i<path.size();i++) {
- cout<<"("<<path[i]/N<<","<<path[i]%N<<")"<<endl;
- }
- return;
- }
- if(finished==false && startx+1<M && matrix[startx+1][starty]!=1) findPath(path,startx+1,starty,endx,endy);
- if(finished==false && startx-1>0 && matrix[startx-1][starty]!=1) findPath(path,startx-1,starty,endx,endy);
- if(finished==false && starty+1<N&&matrix[startx][starty+1]!=1) findPath(path,startx,starty+1,endx,endy);
- if(finished==false && starty-1>0&&matrix[startx][starty-1]!=1) findPath(path,startx,starty-1,endx,endy);
- path.pop_back();
- flag[startx][starty]=0;
- }