您的位置:首页 > 其它

SDAU课程练习2 1016

2016-04-02 16:47 225 查看


Red and Black


Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 5   Accepted Submission(s) : 4


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.<br><br>Write
a program to count the number of black tiles which he can reach by repeating the moves described above. <br>

 

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.<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>

 

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). <br>

 

Sample Input

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>

 

Sample Output

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

 

Source

Asia 2004, Ehime (Japan), Japan Domestic

 
题目大意:

从 @ 出发,只可以走  .     问最多可以走多少  .   

思路:

老师是按照  dfs  来讲的,因为这个是让求最长路 一般 bfs  是求最短路的。不过我是用  bfs  来写的。

感想:

感觉  bfs  比  dfs  简单一些,因为  bfs  套路起来比较简单。。。

AC代码:

#include<iostream>
#include<string.h>
#include<queue>
#include<stdio.h>
using namespace std;

char mapp[205][205];
int vis[205][205];
int n,sx,sy,m;
int dirx[5]={0,0,1,-1};
int diry[5]={1,-1,0,0};
struct point
{
int x;
int y;
};
int isend(int x,int y)
{
if(x<0||y<0||x>=n||y>=m||vis[x][y]||mapp[x][y]=='#')
return 1;
return 0;
}
int bfs()
{
queue<point>que;
point now,next;
now.x=sx;
now.y=sy;
que.push(now);
int i;
while(!que.empty())
{
now=que.front();
que.pop();
vis[now.x][now.y]=1;
for(i=0;i<4;i++)
{
next.x=now.x+dirx[i];
next.y=now.y+diry[i];
if(isend(next.x,next.y))
continue;
else
{
que.push(next);
}
}
}
return 0;
}

int main()
{
int i,j;
//freopen("r.txt","r",stdin);
while(~scanf("%d%d",&m,&n))
{
if(n==0&&m==0) break;
for(i=0;i<n;i++)
{
scanf("%s",mapp[i]);
for(j=0;j<m;j++)
if(mapp[i][j]=='@')
{
sx=i;sy=j;
}
}
memset(vis,0,sizeof(vis));
bfs();
int num=0;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
if(vis[i][j])
num++;
}
cout<<num<<endl;
}

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