Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 28659 | Accepted: 15614 |
Description
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
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
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
Source
簡單的DFS,練練手,直接代碼吧。
Source Code
Problem: 1979 User: lk951208
Memory: 252K Time: 0MS
Language: C++ Result: Accepted
Source Code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 300
using namespace std;
char mp[MAXN][MAXN];
int N,M,ans;
void dfs(int r,int c)
{
if(r<0 || r>=M || c<0 || c>=N) return;
if(mp[r][c]=='#') return;
if(mp[r][c]!='#') {ans++;mp[r][c]='#';}
dfs(r+1,c);
dfs(r-1,c);
dfs(r,c+1);
dfs(r,c-1);
}
int main()
{
while(scanf("%d%d",&N,&M) && N && M)
{
int x,y;ans=0;
memset(mp,0,sizeof(mp));
for(int i=0;i<M;i++)
{
scanf("%s",mp[i]);
for(int j=0;j<N;j++)
if(mp[i][j]=='@') {x=i;y=j;}
}
dfs(x,y);
printf("%d\n",ans);
}
return 0;
}