题目
给一个n*m的点矩阵,如何不重复的一步走完所有点。
输入
n, m 代表矩阵的行和宽,n和m不同时为1(1<=n<=m<10^5)。
输出
x, y 代表起始位点的坐标(1<=x<=n,1<=y<=m)。
'W' 'S' 'A' 'D' 代表方向上下左右
比如
输入
3 3
输出
0 0
SSDWWDSS
题目分析
这道题目使用的是图论的深度搜索。
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int n, m;
vector<vector<bool>> visited;
bool isValid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m && !visited[x][y];
}
bool dfs(int x, int y, int steps, string& path) {
if (steps == n * m) {
return true; // 所有格子都已访问过,成功找到路径
}
// 方向数组,代表上下左右(W, S, A, D)
int dirX[4] = {-1, 1, 0, 0};
int dirY[4] = {0, 0, -1, 1};
char dirLabel[4] = {'W', 'S', 'A', 'D'};
for (int i = 0; i < 4; i++) {
int newX = x + dirX[i];
int newY = y + dirY[i];
if (isValid(newX, newY)) {
visited[newX][newY] = true;
path.push_back(dirLabel[i]); // 添加方向到路径
if (dfs(newX, newY, steps + 1, path)) {
return true; // 找到有效路径,递归终止
}
path.pop_back(); // 回溯
visited[newX][newY] = false;
}
}
return false;
}
void findPath(){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
visited = vector<vector<bool>>(n, vector<bool>(m, false));
string path = "";
visited[i][j] = true; // 标记起点已访问
if(dfs(i, j, 1, path)){
cout << "Start at (" << i << ", " << j << ")" << endl;
cout << "Complete path: " << path << endl;
return;
}
}
}
cout << "No path found in the matrix." << endl;
}
int main() {
cin>>n>>m;
findPath();
}