递归过程会自动利用栈,可以大大简化过程
#include<stdio.h> #define N 10 int vis[N][N], done = 0; char maze[N][N + 1]; int dx[]={0,1,0,-1}; int dy[]={1,0,-1,0}; void dfs(int x, int y) { int i; if(done || maze[x][y] == ‘#‘ || vis[x][y]) return; if(maze[x][y] == ‘E‘) { //exit maze[x][y] = ‘*‘; done = 1; return; } maze[x][y] = ‘*‘; vis[x][y] = 1; for(i = 0; i < 4; i++) dfs(x + dx[i], y + dy[i]); if(!done) maze[x][y] = ‘!‘; } int main() { int i; for(i = 0; i < 10; i++) gets(maze[i]); dfs(1, 1); for(i = 0; i < 10; i++) puts(maze[i]); return 0; }
时间: 2024-12-09 06:04:49