题解
【基础】迷宫的第一条出路
3 条题解
-
0
#include <bits/stdc++.h> using namespace std; char a[25][25]; bool vis[25][25]; int hang[400], lie[400]; int n, s; bool flag = false; int dx[4] = {0, -1, 0, 1}; int dy[4] = {-1, 0, 1, 0}; void dfs(int x, int y, int step) { hang[step] = x; lie[step] = y; if (x == n && y == n) { s = step; flag = true; return; } vis[x][y] = true; for (int i = 0; i < 4; i++) { if (flag) return; int nx = x + dx[i]; int ny = y + dy[i]; if (nx > 0 && nx <= n && ny > 0 && ny <=n && vis[nx][ny] == 0 && a[nx][ny] == '0') { dfs(nx, ny, step + 1); } } } int main(){ cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; } } dfs(1, 1, 1); for (int i = 1; i <= s; i++) { cout << "(" << hang[i] << "," << lie[i] << ")"; if (i < s) { cout << "->"; } } return 0; } -
0
#include <bits/stdc++.h> using namespace std; char a[25][25]; bool vis[25][25]; int hang[400], lie[400]; int n, s; bool flag = false; int dx[4] = {0, -1, 0, 1}; int dy[4] = {-1, 0, 1, 0}; void dfs(int x, int y, int step) { hang[step] = x; lie[step] = y; if (x == n && y == n) { s = step; flag = true; return; } vis[x][y] = true; for (int i = 0; i < 4; i++) { if (flag) return; int nx = x + dx[i]; int ny = y + dy[i]; if (nx > 0 && nx <= n && ny > 0 && ny <=n && vis[nx][ny] == 0 && a[nx][ny] == '0') { dfs(nx, ny, step + 1); } } } int main(){ cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; } } dfs(1, 1, 1); for (int i = 1; i <= s; i++) { cout << "(" << hang[i] << "," << lie[i] << ")"; if (i < s) { cout << "->"; } } return 0; } -
0
#include<bits/stdc++.h> using namespace std; //迷宫路径 int dx[5]={0,0,-1,0,1};//四个方向设置好 左上右下 int dy[5]={0,-1,0,1,0}; int n; char a[101][101]; int v[401][3];//储存每次可以走的点,通过返回更新路径,能到终点输出更新的路径 //每次走的点以及数量 void dfs(int x,int y,int k){ v[k][1]=x; v[k][2]=y; a[x][y]='1';//走过标记 if(x==n&&y==n){//走到终点打印路径 cout<<"(1,1)"; for(int i=2;i<=k;i++){ cout<<"->("<<v[i][1]<<","<<v[i][2]<<")"; } return ; } for(int i=1;i<=4;i++){ int tx=x+dx[i]; int ty=y+dy[i];//四方向 if(a[tx][ty]=='0'){ dfs(tx,ty,k+1); //每走一个点就记录一个,不能走进行后退 } } } int main(){ cin>>n;//n行n列 for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cin>>a[i][j];//读入每个点的情况 } } //从1,1 点开始每次记录一个能走的点 dfs(1,1,1); return 0; }
- 1