`
java-mans
  • 浏览: 11439176 次
文章分类
社区版块
存档分类
最新评论

hdu1312 赤裸BFS

 
阅读更多

Red and Black

Time Limit: 2000/1000 MS (Java/Others)Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3893Accepted Submission(s): 2505


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
一个纯的BFS 赤裸裸的BFS 一开始wa在按照自己的斯洛没有考虑到类似这种####@数据 也就是ans=1的时候的情狂
#include<stdio.h> #include<string.h> int a[22][22],w,h; int c[4][2]={1,0,0,1,-1,0,0,-1}; int s_x,s_y; struct haha { int x; int y; }q[1000000]; int bfs() { int head=0,tail=1,ans=0,i,x1,y1; q[1].x=s_x;q[1].y=s_y; while(head<tail) { ++head; for(i=0;i<4;i++) { x1=q[head].x+c[i][0]; y1=q[head].y+c[i][1]; if(a[x1][y1]!=0)//&&x1>0&&x1<=h&&y1>0&&y1<=w { //printf("a[%d][%d]=%d",x1,y1,a[x1][y1]); ans++; a[x1][y1]=0; q[++tail].x=x1; q[tail].y=y1; } } } if(ans==0) return 1;//一开始把这里忘了 由于每次找到能走的则加加 else//最后一次加加相当于多加了一次 我把他当做原始位置的那一个了 但是忘记了考虑 return ans;//当只有原始位置的时候 它不能进入循环 ans=0 但是原始位置的那次没加上 } int main() { int i,j,ans; char ch; while(scanf("%d %d",&w,&h)==2) { getchar(); if(w<=0||h<=0) return 0; memset(a,0,sizeof(a)); ans=1; for(i=1;i<=h;i++) { for(j=1;j<=w;j++) {ch=getchar(); if(ch=='@'){s_x=i;s_y=j;a[i][j]=1;}//printf("s_x=%d,s_y=%d\n",s_x,s_y); if(ch=='.') a[i][j]=1; if(ch=='#') a[i][j]=0; } getchar(); } ans=bfs(); printf("%d\n",ans); } return 0; }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics