迷宫是一个二维矩阵,其中1为墙,0为路,3为入口,4为出口.要求从入口开始,从出口结束,按照 下,左,上,右 的顺序来搜索路径.
输入迷宫宽度w 迷宫高度h
迷宫第一行
迷宫第二行
…
迷宫第h 行
入口横坐标1 入口纵坐标1
横坐标2 纵坐标2
横坐标3 纵坐标3
横坐标4 纵坐标4
…
横坐标n-1 纵坐标n-1
出口横坐标n 出口纵坐标n
8 10
1 1 1 1 1 1 1 1
1 0 1 1 0 1 0 1
1 0 1 0 0 1 0 1
1 1 0 3 1 0 1 1
1 0 0 1 0 0 4 1
1 0 0 0 0 1 1 1
1 0 1 0 0 1 0 1
1 0 1 0 0 0 1 1
1 1 1 1 0 0 0 1
1 1 1 1 1 1 1 1
3 3
2 3
2 4
2 5
3 5
3 6
3 7
4 7
4 6
4 5
4 4
5 4
6 4
基本思路:这是一个非常经典的DFS的运用。DFS的思想就是一条路走到黑,然后往回走。
#include#include #include using namespace std; int dir[4][2] = { {1,0},//下 {0,-1},//左 {-1,0},//上 {0,1}//右 }; int w, h, ex, ey, sx, sy; struct Node { int x, y; Node() = default; Node(int X, int Y) : x(X), y(Y) {} }; stack s, t; int** map; Node temp; bool check(int x, int y) { if (x < h && x >= 0 && y >= 0 && y < w) return true; else return false; } bool DFS(int dh, int dw) { temp.x = dh; temp.y = dw; s.push(temp); if (dh == ex && dw == ey)//判断当前点是否是出口 return true; for (int i = 0; i < 4; ++i) {//寻找当前点四个方向上的点 int th = dh + dir[i][0], tw = dw + dir[i][1]; if (check(th, tw) && map[th][tw] != 1) {//如果能走通,就一直走, map[dh][dw] = 1;//标记当前点 if (DFS(th, tw)) return true; } } s.pop();//如果四个方向都走不通,说明这个点是错误的,弹出栈。往回走 return false; } int main() { cin >> w >> h; map = new int* [h]; for (int i = 0; i < h; i++) map[i] = new int[w]; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { cin >> map[i][j]; if (map[i][j] == 3) { sx = i; sy = j; } if (map[i][j] == 4) { ex = i; ey = j; } } } DFS(sx, sy); while (!s.empty()) { Node iter; iter = s.top(); t.push(iter); s.pop(); } while (!t.empty()) { cout << t.top().y << " " << t.top().x << endl; t.pop(); } return 0; }
欢迎交流



