膜拜前面各位大佬,写一个最简单的辣鸡深度遍历
迷宫问题
http://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc
#include <bits/stdc++.h> using namespace std; int N = 0, M = 0; int pathlen = INT_MAX; vector<vector<bool>> rec; vector<pair<int, int>> pathrec; void dfs(vector<vector<bool>> &maze, \ vector<pair<int, int>> &path, \ pair<int, int> cur, int len) { if (cur.first == N-1&&cur.second == M-1) { len++; path.push_back(cur); if (pathlen>=len) { pathrec = path; pathlen = len; } path.pop_back(); return; } else { int i = cur.first; int j = cur.second; rec[i][j] = true; path.push_back(make_pair(i, j)); len++; // 向上 if (i - 1 >= 0 &&( maze[i - 1][j] != true )&& (rec[i - 1][j] != true)) { dfs(maze, path, make_pair(i - 1, j), len); } // 向下 if (i + 1<N&&(maze[i + 1][j] != true )&&( rec[i + 1][j] != true)) { dfs(maze, path, make_pair(i + 1, j), len); } // 向左 if (j - 1 >= 0 && (maze[i][j - 1] != true) && (rec[i][j - 1] != true)) { dfs(maze, path, make_pair(i, j - 1), len); } // 向右 if (j + 1<M&&(maze[i][j + 1] != true) && (rec[i][j + 1] != true)) { dfs(maze, path, make_pair(i, j + 1), len); } len--; path.pop_back(); rec[i][j] = false; } } int main() { // 深度优先遍历 while (cin >> N >> M) { vector<vector<bool>> maze(N, vector<bool>(M, 0)); int tn;tn = N; int tm;tm = M; // 迷宫输入完成 for (int i = 0; i<N; i++) { for (int j = 0; j<M; j++) { int td; cin >> td; maze[i][j] = (td == 1) ? true : false; } } rec = maze; // 已经经过的路径记录 vector<pair<int, int>> path; dfs(maze, path, make_pair(0, 0), 0); for (int i = 0; i<pathrec.size(); i++) { cout << '(' << pathrec[i].first << ',' << pathrec[i].second << ')' << endl; } pathrec.clear(); rec.clear(); path.clear(); maze.clear(); pathlen = INT_MAX; } return 0; }