算法流程图
栈
队列
代码实现
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class Node
{
public:
Node(int a=0,int b=0,int c=0):x(a),y(b),di(c){}
int x;
int y;
int di;
};
int map[15][15] = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,1,1,1,0,0,0,0,1,1,1},
{1,1,0,1,1,1,1,1,0,1,1,0,1,1,1},
{1,1,0,1,1,1,1,1,1,1,1,0,1,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,1,1,1},
{1,1,1,1,1,0,1,1,1,1,1,0,1,1,1},
{1,1,1,1,1,0,0,1,1,1,0,0,1,1,1},
{1,1,1,1,1,1,0,0,1,1,0,1,1,1,1},
{1,1,1,1,1,1,1,0,1,1,0,1,1,1,1},
{1,1,1,1,0,0,0,0,1,1,0,1,1,1,1},
{1,1,1,1,1,1,1,0,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,0,1,1,1,1,1,1,1},
{1,1,1,1,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};
int passed[15][15] = { 0 };
bool PassC(int x, int y)
{
if (!map[x][y] && !passed[x][y])
return true;
else
return false;
}
Node NextNode(Node temp)
{
switch (temp.di)
{
case 1:
temp.y++;
break;
case 2:
temp.x++;
break;
case 3:
temp.y--;
break;
case 4:
temp.x--;
break;
default:
break;
}
temp.di = 1;
return temp;
}
bool MazePathStack(stack<Node>& temp)
{
Node present(1, 1, 1);
while (true)
{
if (PassC(present.x, present.y))
{
temp.push(present);
passed[present.x][present.y] = 1;
if (present.x == 13 && present.y == 13)
return true;
present=NextNode(present);
}
else
{
while (!temp.empty())
{
Node *t = &temp.top();
if (t->di != 4)
{
t->di++;
present = NextNode(*t);
break;
}
else
temp.pop();
}
if (temp.empty())
return false;
}
}
}
bool MazePathQueue(queue<Node>&temp)
{
Node present(1, 1, 1);
while (true)
{
if (PassC(present.x, present.y))
{
temp.push(present);
passed[present.x][present.y] = 1;
if (present.x == 13 && present.y == 13)
return true;
present = NextNode(present);
}
else
{
while (!temp.empty())
{
Node *t = &temp.back();
if (t->di != 4)
{
t->di++;
present = NextNode(*t);
break;
}
else
{
queue<Node> newq;
while (!(temp.front().x == t->x && temp.front().y == t->y))
{
newq.push(temp.front());
temp.pop();
}
temp.pop();
temp = newq;
}
}
if (temp.empty())
return false;
}
}
}
int main()
{
stack<Node>path;
queue<Node>Path;
Node point;
int choice;
cout << "栈实现输入1,队列实现输入2";
cin >> choice;
if (choice == 1)
{
if (MazePathStack(path))
while (!path.empty())
{
point = path.top();
cout << ++point.x << ":" << ++point.y << ",";
path.pop();
}
else
cout << "路径不存在!";
}
else
{
if (MazePathQueue(Path))
{
while (!Path.empty())
{
point = Path.front();
cout << ++point.x << ":" << ++point.y << ",";
Path.pop();
}
}
else
cout << "路径不存在!";
}
return 0;
}