#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 100 int maze[MAXN][MAXN]; int vis[MAXN][MAXN]; int queue[MAXN*MAXN]; //队列 int fa[MAXN][MAXN]; // 父结点 int dx[]={0,0,-1,1}; int dy[]={-1,1,0,0}; int n,m; //n为行 m为列 void bfs(int x, int y){ int front, rear, u, d; front = rear = 0; u = x*m+y; queue[rear++] = u; vis[x][y] = 1; fa[x][y] = u; //起点的父结点为它本身 while(front < rear){ u = queue[front++]; x = u/m; y = u%m; for(d=0; d<4; d++){ int nx = x+dx[d]; int ny = y+dy[d]; if(nx >=0 && nx <n && ny >=0 && ny < m && !vis[nx][ny] && maze[nx][ny]){ int v = nx*m+ny; fa[nx][ny]=u; queue[rear++]=v; vis[nx][ny]=1; if(nx == n-1 && ny == m-1) return ; } } } } void print_path(int x, int y){ //从终点 int nx = fa[x][y] / m; int ny = fa[x][y] % m; if(nx != x || ny != y){ print_path(nx, ny); printf("(%d,%d)->(%d,%d)\n", nx, ny, x, y); } } int main ( ){ freopen("d:\\my.txt", "r", stdin); memset(vis, 0, sizeof(vis)); memset(maze, 0, sizeof(maze)); int i,j; scanf("%d %d", &n, &m); for(i=0; i<n; i++) for(j=0; j<m; j++) scanf("%d", &maze[i][j]); bfs(0,0); print_path(n-1, m-1); return 0; }