迷宮問題的DFS解決(非最短)
阿新 • • 發佈:2018-12-17
#include <iostream> #include<stack> #include<queue> using namespace std; int a[7][7]= {{1,1,1,1,1,1,1}, {1,0,0,0,0,0,1}, {1,0,1,0,1,0,1}, {1,0,1,1,0,0,1}, {1,0,1,1,0,1,1}, {1,0,0,0,0,0,1}, {1,1,1,1,1,1,1} }; struct Point{ int row; int col; int p=0; Point(int x,int y):row(x),col(y),p(0) {}; bool operator ==(const Point &rhs) { if(this->row==rhs.row&&this->col==rhs.col) return true; else return false; } }; //判斷當前的位置是否可以通過 int pass(Point node) { if(a[node.row][node.col]==0&&node.p==0) return 1; else return 0; } //當前位置移動到下一塊 Point nextpos(Point n,int direction) { if(direction==1) n.col++; if(direction==2) n.row++; if(direction==3) n.col--; if(direction==4) n.row--; n.p=0; return n; } void F (Point n,Point m) { if(!(n == m)) cout<<"OK"<<endl; } //尋找路徑 void Findnode(int a[7][7], const Point &startnode, const Point &endnode) { stack<Point>Q; Point curnode = startnode; while (!(curnode == endnode)) { //cout<<"diyibu"<<endl; int key = 1; while (pass(curnode)) {//cout<<"dierbu"<<endl; if (curnode == endnode) { break; } Q.push(curnode); //a[curnode.row][curnode.col]=1; curnode.p = 1; curnode = nextpos(curnode, 1); }//將可以通過的位置入棧 if (curnode == endnode) { break; } curnode = Q.top(); for (int i = 2; i <= 4; i++) { //cout<<"disanbu"<<endl; curnode = nextpos(curnode, i); if (pass(curnode)) break; if (i == 4) key = -1; }//遍歷4個方向 if (key == -1) Q.pop();//如果四個方向都不行就出棧 } if (Q.empty()) { cout << "find false" << endl; return; }//如果沒有路徑輸出find false else { Q.push(endnode); } while (!Q.empty()) { Point n = Q.top(); cout << "(" << n.row << "," << n.col << ")" << " "; Q.pop(); } //反向輸出路徑 } int main() { Point startnode(1,1); Point endnode (5,5); //cout<<(endnode==startnode)<<endl; //cout<<nextpos(startnode,1).row<<nextpos(startnode,1).col; //F(startnode,endnode); Findnode(a,startnode,endnode); return 0; }