您的位置:首页 > 其它

POJ_1979_Red and Black

2016-10-23 16:18 309 查看
POJ 1979

题意:求人(@)能踩到的白块数(.),只能上下左右移动!
思路:基础的dfs,直接回溯一下就好, 或者bfs把所有的白块都踩一遍并记录。


/*****
DFS
*****/
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>

#define PI acos(-1.0)
#define eps 1e-10
#define INF 0x7fffffff
#define debug(x) cout << "--------------> " << x << endl

typedef long long LL;
typedef unsigned long long ULL;

using namespace std;

int n,m,ret;
int vis[27][27];        //标记是否遍历过
char graph[27][27];
int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};  //方向数组

void dfs(int x,int y)
{
vis[x][y] = 1;
for(int i = 0; i < 4; ++i)
{
int xx = x + dx[i],yy = y + dy[i];
//要判断一下是否出界,由于比较简单就不比多写函数
if(xx >= 0 && xx < m && yy >=0 && yy < n)
{
if(graph[xx][yy] == '.' && !vis[xx][yy])
{
ret++;
vis[xx][yy] = 1;
dfs(xx,yy);
}
}
}
}

int main()
{
while(scanf("%d%d",&n,&m) , n + m)
{
bool flag = true;
ret = 0;
memset(vis,0,sizeof(vis));
for(int i = 0; i < m; ++i)
{
scanf("%s",&graph[i]);
}
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if(graph[i][j] == '@')
{
ret++;
dfs(i,j);
flag = false;
break;
}
}
if(!flag)break;
}
printf("%d\n",ret);
}
return 0;
}


/*****
BFS
*****/
#include <iostream>
#include <iomanip>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>

#define debug(x) cout << "--------------> " << x << endl

using namespace std;

const double PI = acos(-1.0);
const double eps = 1e-10;
const long long INF = 0x7fffffff;
const long long MOD = 1000000007;
const int MAXN = 20 + 7;

int n, m, ans;
char gra[MAXN][MAXN];
bool vis[MAXN][MAXN];

int dx[] = { 1, 0, -1, 0 };
int dy[] = { 0, 1, 0, -1 };

bool isValidRoad(int x, int y)
{
return (x >= 0) && (y >= 0) && (x < m) && (y < n) && !vis[x][y];      //x is the index of row while y is column
}

class Point
{
public:
Point(int a, int b) :x(a), y(b){};
int x, y;
};

void bfs(int x, int y)
{
Point p(x, y);
queue<Point> q;
q.push(p);
memset(vis, 0, sizeof(vis));
vis[x][y] = true;
while  (!q.empty() )
{
Point P = q.front();
ans++;
q.pop();
for (int i = 0; i < 4; ++i)
{
if (isValidRoad(P.x + dx[i], P.y + dy[i]) && (gra[P.x + dx[i]][P.y + dy[i]] == '.' || gra[P.x + dx[i]][P.y + dy[i]] == '@'))
{
Point vertex(P.x + dx[i], P.y + dy[i]);
q.push(vertex);
vis[P.x + dx[i]][P.y + dy[i]] = true;
}
}
}
}

int main()
{
while (cin >> n >> m,  n + m)  // n is column while m is row
{
memset(gra, 0, sizeof(gra));
ans = 0;
int x, y;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
cin >> gra[i][j];
if (gra[i][j] == '@')
{
x = i;
y = j;
}

}
}
bfs(x, y);
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: