1 条题解
-
0
解题思路
-
输入处理:
- 持续读取迷宫信息,包括行数
row
、列数col
、起点坐标(str, stc)
、终点坐标(edr, edc)
,直到列数为 0 时结束输入。 - 读取每个格子的状态信息存入
grid
数组。
- 持续读取迷宫信息,包括行数
-
深度优先搜索(DFS):
dfs
函数用于从起点开始搜索到终点的路径。- 递归过程中,若当前格子已访问过则返回
false
。 - 若到达终点,标记该格子的路径编号并返回
true
。 - 依次尝试向左、上、右、下四个方向移动,满足移动条件(如无墙阻挡)则递归调用
dfs
函数。 - 若四个方向都无法找到路径,将该格子路径编号置为 0 并返回
false
。
-
输出迷宫及路径:
print
函数按特定格式输出迷宫及路径。- 用
+
和-
绘制迷宫的边界和分隔线。 - 根据
path
数组的值,在相应格子中输出路径编号或占位符。
-
多组数据处理:
- 对于每组输入数据,重置访问标记和路径数组,调用
dfs
函数搜索路径,再调用print
函数输出结果。
- 对于每组输入数据,重置访问标记和路径数组,调用
#include<iostream> #include<cstring> using namespace std; int col,row,str,stc,edr,edc; int grid[15][15]; int path[15][15]; bool visit[15][15]; bool dfs(int r, int c, int id){ //cout << r << " " << c << endl; if(visit[r][c]) return 0; if(r==edr-1&&c==edc-1){ path[r][c] = id; return 1; } //cout << grid[r][c] << endl; visit[r][c] = 1; if(c>0&&(grid[r][c-1]%2==0)){ if(dfs(r,c-1,id+1)){ path[r][c] = id; return 1; } } if(r>0&&(grid[r-1][c]<2)){ if(dfs(r-1,c,id+1)){ path[r][c] = id; return 1; } } if(c<col-1&&grid[r][c]%2==0){ if(dfs(r,c+1,id+1)){ path[r][c] = id; return 1; } } if(r<row-1&&grid[r][c]<2){ if(dfs(r+1,c,id+1)){ path[r][c] = id; return 1; } } path[r][c] = 0; return 0; } void print(int nc){ cout << "Maze " << nc << endl; cout << endl; cout << "+"; for(int i = 0; i < col; i++) cout << "---+"; cout << endl; for(int i = 1; i < 2*row; i++) if(i%2){ cout << "|"; for(int j = 0; j < col; j++){ if(path[i/2][j]==0) cout << "???"; else if(path[i/2][j]==-1) cout<<" "; else if(path[i/2][j]<10) cout << " " << path[i/2][j]; else if(path[i/2][j]<100) cout << " " << path[i/2][j]; else cout << path[i/2][j]; if(grid[i/2][j]%2||j==col-1) cout << "|"; else cout << " "; } cout << endl; } else{ cout << "+"; for(int j = 0; j < col; j++){ //cout << i/2-1 << " " << col << " " <<grid[i/2-1][col]; if(grid[i/2-1][j]>=2) cout << "---"; else cout << " "; cout << "+"; } cout << endl; } cout << "+"; for(int j = 0; j < col; j++) cout << "---+"; cout << endl; } int main(){ int nc = 1; while(cin>>row>>col>>str>>stc>>edr>>edc&&(col)){ memset(visit,0,sizeof(visit)); memset(path,-1,sizeof(path)); for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) cin >> grid[i][j]; dfs(str-1,stc-1,1); print(nc); nc++; cout << endl; cout << endl; } }
-
- 1
信息
- ID
- 308
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者