UVA784 UVALive5280 Maze Exploration【DFS】
A maze of rectangular rooms is represented on a two dimensional grid as illustrated in figure 1a. Each point of the grid is represented by a character. The points of room walls are marked by the same character which can be any printable character different than ‘’, ‘ ’ and space. In figure 1 this character is ‘X’. All the other points of the grid are marked by spaces.
Figure 1. Mazes of rectangular rooms
All rooms of the maze are equal sized with all walls 3 points wide and 1 point thick as illustrated in figure 2. In addition, a wall is shared on its full length by the separated rooms. The rooms can communicate through doors, which are positioned in the middle of walls. There are no outdoor doors.
Figure 2. A room with 3 doors
Your problem is to paint all rooms of a maze which can be visited starting from a given room, called the ‘start room’ which is marked by a star (‘’) positioned in the middle of the room. A room can be visited from another room if there is a door on the wall which separates the rooms. By convention, a room is painted if its entire surface, including the doors, is marked by the character ‘#’ as shown in figure 1b.
Input
The program input is a text file structured as follows:
- The first line contains a positive integer which shows the number of mazes to be painted.
- The rest of the file contains the mazes.
The lines of the input file can be of different length. The text which represents a maze is terminated by a separation line full of underscores (‘ ’). There are at most 30 lines and at most 80 characters in a line for each maze. The program reads the mazes from the standard input.
Output
The output text of a painted maze has the same format as that which has been read for that maze,
including the separation lines. The program writes the painted mazes on the standard output.
Sample Input
2
XXXXXXXXX
X X X
X * X
X X X
XXXXXXXXX
X X
X X
X X
XXXXX
XXXXX
X X
X * X
X X
XXXXX
Sample Output
XXXXXXXXX
X###X###X
X#######X
X###X###X
XXXXXXXXX
X X
X X
X X
XXXXX
XXXXX
X###X
X###X
X###X
XXXXX
Regionals 1995 >> Europe - Southeastern
问题链接:UVA784 UVALive5280 Maze Exploration
问题简述:(略)
问题分析:
类似迷宫问题,读懂题应该就没有问题了。
还是递归的DFS函数让程序更加简洁。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA784 UVALive5280 Maze Exploration */
#include <bits/stdc++.h>
using namespace std;
const int R = 30;
const int C = 80;
char maze[R + 1][C + 1];
int rows;
void dfs(int r, int c)
{
if(r >= 0 && r < rows && c >= 0 && maze[r][c] == ' ') {
maze[r][c] = '#';
dfs(r - 1, c);
dfs(r, c + 1);
dfs(r + 1, c);
dfs(r, c - 1);
}
}
int main()
{
int t;
scanf("%d", &t);
getchar();
while(t--) {
for(rows = 0; gets(maze[rows]) && maze[rows][0] != '_'; rows++);
for(int i = 0; i < rows; i++)
for(int j = 0; maze[i][j]; j++)
if(maze[i][j] == '*') {
maze[i][j] = ' ';
dfs(i, j);
i = rows;
break;
}
for(int i = 0; i <= rows; i++)
puts(maze[i]);
}
return 0;
}