poj 1979 Red and Black
Red and Black
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 25228 | Accepted: 13605 |
Description
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
/* 题意:给你一个n*m的矩阵,字符@是起点字符.是路字符#是墙,问你 从起点开始最多可以走多长的路(即可以走过多少个点,注意:墙不可穿过) 题解:找到起点的坐标,然后向它的四个方向搜索,找到所有的可以走的路 每走过一个点,就在总路数上+1(同样注意将走过的路用#覆盖,避免重复) */ #include<stdio.h> //poj1979 #include<string.h> #include<algorithm> #define MAX 110 #define INF 0x3f3f3f using namespace std; int n,m,j,i,t,k; int sum; char map[MAX][MAX]; int vis[MAX][MAX]; //int move[4][2]={1,0,-1,0,0,-1,0,1}; //此题不能用这个辅助数组,因为这个辅助数组走一步之后起点的 //(x,y)的坐标发生了变化,而走过的路已经被覆盖,导致无法再走 void dfs(int x,int y) { if(0<=x&&x<m&&0<=y&&y<n&&map[x][y]!='#') { map[x][y]='#'; sum++; dfs(x+1,y); dfs(x-1,y); dfs(x,y-1); dfs(x,y+1); //这样搜索,由于搜索一次后(x,y)并没有改变就不会有上边的问题 // for(i=0;i<4;i++) // dfs(x+move[i][0],y+move[i][1]); } return ; } int main() { int x,y; while(scanf("%d%d",&n,&m),n|m) { sum=0; for(i=0;i<m;i++) scanf("%s",map[i]); for(i=0;i<m;i++) for(j=0;j<n;j++) if(map[i][j]=='@')//找到起点坐标并记录下来 { x=i; y=j; } dfs(x,y); printf("%d\n",sum); } return 0; }