您的位置:首页 > 其它

练习二1016

2016-04-16 11:02 351 查看
Red and Black

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 23   Accepted Submission(s) : 13
[align=left]Problem Description[/align]
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.<br><br>Write a program to count the number of black tiles which he can reach by repeating the moves described above. <br>
 

[align=left]Input[/align]
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.<br><br>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.<br><br>'.' - a black tile <br>'#' - a red tile <br>'@' - a man on a black tile(appears exactly once in a data set) <br>
 

[align=left]Output[/align]
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). <br>
 

[align=left]Sample Input[/align]

6 9<br>....#.<br>.....#<br>......<br>......<br>......<br>......<br>......<br>#@...#<br>.#..#.<br>11 9<br>.#.........<br>.#.#######.<br>.#.#.....#.<br>.#.#.###.#.<br>.#.#..@#.#.<br>.#.#####.#.<br>.#.......#.<br>.#########.<br>...........<br>11 6<br>..#..#..#..<br>..#..#..#..<br>..#..#..###<br>..#..#..#@.<br>..#..#..#..<br>..#..#..#..<br>7 7<br>..#.#..<br>..#.#..<br>###.###<br>...@...<br>###.###<br>..#.#..<br>..#.#..<br>0 0<br>

 

[align=left]Sample Output[/align]

45<br>59<br>6<br>13<br>

 

[align=left]Source[/align]
Asia 2004, Ehime (Japan), Japan Domestic
 

Statistic |

Submit |
Back
题意:
房间里用红和黑色的瓷砖覆盖,站在一块黑砖上,只能上下左右移动到黑转上,问可以经过多少黑砖,可以重复经过。
思路:
一个简单地深搜,先找到起点@开始搜索,注意题目中的w代表列,h代表行。
代码:

#include<iostream>

#include<string.h>

using namespace std;

int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}},w,h,mov;

char map[21][21];

int vis[21][21];

bool inmap(int a,int b)

{

if(a>=1&&a<=h&&b>=1&&b<=w) return true;

return false;

}

void dfs(int a,int b)

{

for(int i=0;i<4;i++)

{

if(!inmap(a+dir[i][0],b+dir[i][1]))

continue;

if(vis[a+dir[i][0]][b+dir[i][1]])

continue;

if(map[a+dir[i][0]][b+dir[i][1]]=='#')

continue;

mov++;

vis[a+dir[i][0]][b+dir[i][1]]=1;

dfs(a+dir[i][0],b+dir[i][1]);

}

}

int main()

{

while(cin>>w>>h&&w&&h)

{

int i,j,k,t,x,y;

memset(vis,0,sizeof(vis));

for(i=1;i<=h;i++){

for(j=1;j<=w;j++){

cin>>map[i][j];

}

}

for(k=1;k<=h;k++){

for(t=1;t<=w;t++){

if(map[k][t]=='@')

{x=k;y=t;mov=1;}

}

}

vis[x][y]=1;

dfs(x,y);

cout<<mov<<endl;

}

return 0;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: