- #include <iostream>
- #include <cstring>
- #include <list>
- using namespace std;
- struct coor {
- int x, y;
- bool operator == (coor a)
- {
- if(a.x == x && a.y == y) return true;
- else return false;
- }
- coor operator += (coor a)
- {
- x += a.x, y += a.y;
- return *this;
- }
- coor operator -= (coor a)
- {
- x -= a.x, y -= a.y;
- return *this;
- }
- bool pend(int n, int m)
- {
- if(x >= 0 && y >= 0 && x < m && y < n) return true;
- else return false;
- }
- };
- int n, m;
- int mat[20][20];
- bool vis[20][20], ok = false;
- coor op, ed;
- list<coor> l;
- const coor dir[4] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
- int all;
- void init()
- {
- cout << "Input Row and Col: ";
- cin >> n >> m;
- cout << "Input the matrix:" << endl;
- for(int i = 0; i < n; i++)
- for(int j = 0; j < m; j++) cin >> mat[i][j];
- cout << "Input the entrance coor: ";
- cin >> op.x >> op.y;
- cout << "Input the exit coor: ";
- cin >> ed.x >> ed.y;
- cout << "Input if you wanna see all the solutions(0 / 1): ";
- cin >> all;
- l.push_back(op);
- memset(vis, 0, sizeof(vis));
- }
- void success()
- {
- cout << endl;
- cout << "There'are total " << l.size() << " steps: " << endl;
- for(list<coor>::iterator i = l.begin(); i != l.end(); i++)
- cout << " --> (" << i->x << ", " << i->y << ") <--" << endl;
- }
- void dfs(coor now, coor ed)
- {
- if(now == ed)
- {
- if(!all) ok = true;
- success();
- }
- vis[now.y][now.x] = true;
- for(int i = 0; i < 4; i++)
- {
- now += dir[i];
- if(now.pend(n, m))
- {
- if(!mat[now.y][now.x] && !vis[now.y][now.x])
- {
- l.push_back(now);
- dfs(now, ed);
- l.pop_back();
- }
- if(ok) return;
- }
- now -= dir[i];
- }
- if(all) vis[now.y][now.x] = false;
- }
- int main()
- {
- init();
- dfs(op, ed);
- return 0;
- }
好吧,问题就是:读入一个迷宫,0是空地1是墙,然后DFS出出口。