#問題
Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25498 Accepted Submission(s): 15379
Problem 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.
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)
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
#分析
這是一道圖的遍歷題,我選擇使用DFS,記錄所有到達點的數量即可
#AC碼
#include<iostream>
#include<stdio.h>
#include<string.h>
//point:0可走 -1不可走
//c_cn:0未計數 1已計數
//c_dfs:dfs過程中標記使用
using namespace std;
int cn;
class _Map
{
public:
int point;
int c_dfs;
int c_cn;
_Map()
{
point=0;
c_cn=0;
c_dfs=0;
}
}Map[22][22];
void DFS(int x,int y)
{
Map[x][y].c_dfs=1;
if(!Map[x][y].c_cn)
{
cn++;
Map[x][y].c_cn=1;
}
else //這裏return很有必要,即遇見大量.的時候可以不重複計量
return;
if(!Map[x+1][y].point&&!Map[x+1][y].c_dfs)
{
DFS(x+1,y);
Map[x+1][y].c_dfs=0;
}
if(!Map[x-1][y].point&&!Map[x-1][y].c_dfs)
{
DFS(x-1,y);
Map[x-1][y].c_dfs=0;
}
if(!Map[x][y+1].point&&!Map[x][y+1].c_dfs)
{
DFS(x,y+1);
Map[x][y+1].c_dfs=0;
}
if(!Map[x][y-1].point&&!Map[x][y-1].c_dfs)
{
DFS(x,y-1);
Map[x][y-1].c_dfs=0;
}
return;
}
int main()
{
int x,y;
int cx,cy;
//freopen("1312.txt","r",stdin);
while(cin>>y>>x,x)
{
cn=0;
memset(Map,0,sizeof(Map));
//設置邊界
for(int i=0;i<=y;i++)
{
Map[0][i].point=-1;
Map[x+1][i].point=-1;
}
for(int i=0;i<=x;i++)
{
Map[i][0].point=-1;
Map[i][y+1].point=-1;
}
//錄入地圖
for(int i=1;i<=x;i++)
for(int j=1;j<=y;j++)
{
char ch;
cin>>ch;
if(ch=='#')
Map[i][j].point=-1;
if(ch=='@')
{
cx=i;
cy=j;
}
}
DFS(cx,cy);
cout<<cn<<endl;
}
}