POJ 1979 dfs和bfs两种解法
2013-11-11 11:34
330 查看
fengyun@fengyun-server:~/learn/acm/poj$ cat 1979.cpp
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<iterator>
#include<sstream>//istringstream
#include<cstring>
#include<queue>
using namespace std;
char map[21][21];
char visited[21][21];
int w, h;
int ans;
void dfs(int i, int j)
{
if(i<0||i>=h||j<0||j>=w)
return;
if(map[i][j]=='#')
return;
if(map[i][j]=='.'&&visited[i][j]==0)
{
ans++;
visited[i][j]=1;
dfs(i-1,j);
dfs(i+1,j);
dfs(i,j+1);
dfs(i,j-1);
}
}
int dir[4][2]={
{-1, 0},
{1, 0},
{0, 1},
{0, -1},
};
void bfs(int i, int j)
{
queue<int> q;
q.push(i*w+j);
visited[i][j]=1;
while(!q.empty())
{
//pop
//add neighbors
int ni,nj;
ni=q.front()/w;
nj=q.front()%w;
q.pop();
ans++;
for(int k=0;k<4;k++)
{
int row=ni+dir[k][0];
int col=nj+dir[k][1];
if(row>=0&&row<h&&col>=0&&col<w&&map[row][col]=='.'&&visited[row][col]==0)
{
visited[row][col]=1;
q.push(row*w+col);
}
}
}
}
int main()
{
while(cin>>w>>h && (w||h))
{
int x, y;
memset(visited, 0, sizeof(visited));
ans=0;
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
cin>>map[i][j];
if(map[i][j]=='@')
{
x=i;
y=j;
map[i][j]='.';
}
}
}
//dfs(x,y);
bfs(x,y);
cout<<ans<<endl;
}
return 0;
}
相关文章推荐
- VLAN间单臂路由访问
- 简约的ASP.NET 系统框架,提供源码。
- .NET设计模式(8):适配器模式(Adapter Pattern)
- JavaScript中判断对象类型的几种方法总结
- Big O, Big Omega, Big Theta的含义
- 建立数据库视图
- phpunit mock
- makefile 中使用函数
- 根据字段或者注释查询表清单
- Paoding分词-扩展词典
- 百度词典搜索_grandma
- C# 利用委托和事件 传入一个参数进行进行计算并返回结果
- 文件 Slack 空间信息隐藏
- js将输入的金额转化成每3位一个逗号隔开
- Linux下tar.xz结尾的文件的解压方法
- Python正则表达式指南
- 百度地图覆盖物的描述
- getGenericSuperclass,getSuperclass
- jQuery Django 用load post整个表单
- PHP获取随机数