标签:bfs
题意:一共有四个方向,从’@‘出发,找能到达‘.’的个数, #是不能通过的.
策略:广搜。
这道题属于最简单的bfs了。
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using std::queue;
bool vis[25][25];
char s[25][25];
int n, m;
int ans = 0;
struct node{
int x, y;
};
node st;
const int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int limit(node tmp)
{
return (s[tmp.x][tmp.y]!='#'&&tmp.x>=0&&tmp.x<m&&tmp.y>=0&&tmp.y<n);
}
void bfs()
{
memset(vis, 0, sizeof(vis));
vis[st.x][st.y] = 1;
int i, j;
queue<node> q;
q.push(st);
while(!q.empty()){
node v = q.front();
for( i = 0; i < 4; i ++){
node u;
u.x = v.x+dir[i][0];
u.y = v.y+dir[i][1];
if(!vis[u.x][u.y]&&limit(u)){
++ans;
vis[u.x][u.y] = 1;
q.push(u);
}
}
q.pop();
}
}
int main()
{
int i, j;
while(scanf("%d%d", &n, &m), n||m){
for(i = 0; i < m; i ++){
scanf("%s", s[i]);
}
for(i = 0; i <m; i ++){
for(j = 0; j < n; j ++){
if(s[i][j] == '@'){
st.x = i;
st.y = j;
break;
}
}
}
ans = 1;
bfs();
printf("%d\n", ans);
}
return 0;
}hdoj 1312 Red and Black 【BFS】,布布扣,bubuko.com
标签:bfs
原文地址:http://blog.csdn.net/shengweisong/article/details/38542161