此题为白书数据结构基础图的训练参考
题目链接 http://acm.hust.edu.cn/vjudge/problem/18558
解题思路
图的BFS。代码白书里也写了。
从开始点开始,然后尽情BFS吧。。。
代码
#include<string.h> #include<stdio.h> //#define LOCAL const int maxLen = 100; typedef struct point { int x, y; }Point; char maze[maxLen][maxLen]; //int visit[maxLen][maxLen]; int wei[100], len = 0; int dx[] = {1,-1,0,0}; int dy[] = {0,0,-1,1}; Point q[3000]; void bfs(Point start) { int front = -1, rear = -1; q[++rear] = start; while(front != rear) { Point u = q[++front]; for(int d=0; d<4; d++) { int ux = u.x+dx[d], uy = u.y+dy[d]; if(ux>=0 && ux<len && uy>=0 && uy<wei[ux] && maze[ux][uy]==' ') { Point temp; temp.x = ux; temp.y = uy; q[++rear] = temp; //visit[ux][uy] = 1; maze[ux][uy] = '#'; } } } maze[start.x][start.y] = '#'; } int main() { #ifdef LOCAL freopen("data.txt", "r", stdin); freopen("ans.txt", "w", stdout); #endif int n; scanf("%d", &n); getchar(); while(n--) { char s[maxLen]; Point start; //memset(visit, 0, sizeof(visit)); len = 0; gets(s); while(strchr(s, '_') == NULL) { for(int j=0; j<strlen(s); j++) { if(s[j] == '*') { start.x = len; start.y = j; } maze[len][j] = s[j]; } wei[len] = strlen(s); len++; gets(s); } bfs(start); for(int i=0; i<len; i++) { for(int j=0; j<wei[i]; j++) printf("%c", maze[i][j]); printf("\n"); } puts(s); } return 0; }