您的位置:首页 > 其它

POJ 1979 搜索 水题

2017-08-21 00:00 99 查看
题意:给你一个row*col的矩阵,上面的'#'代表你不能走的地方,'.'表示你能走的地方,'@'表示你的起点,问你最多能走多少格。

dfs

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char s[21];

void dfs(int x, int y){
mp[x][y] = 0;
for (int k = 0; k < 4; k++){
int nx = x + dir[k][0], ny = y + dir[k][1];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && mp[nx][ny]){
ans++;
dfs(nx, ny);
}
}
}
int main(){
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);

int x, y;
while (scanf("%d%d", &m, &n), n + m){
for (int i = 0; i < n; i++){
scanf("%s", s);
for (int j = 0; j < m; j++){
mp[i][j] = (s[j] == '#' ? 0 : 1);
if (s[j] == '@')
x = i, y = j;
}
}
ans = 1;
dfs(x, y);
printf("%d\n", ans);
}
return 0;
}


bfs

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char s[21];

struct Node {
int x, y;
};
int bfs(Node st){
int cnt = 1;
queue<Node> q;
q.push(st);
Node t;
mp[st.x][st.y] = 0;
while (!q.empty()){
Node nd = q.front();
q.pop();
for (int k = 0; k < 4; k++){
t.x = nd.x + dir[k][0], t.y = nd.y + dir[k][1];
if (t.x >= 0 && t.y >= 0 && t.x < n && t.y < m && mp[t.x][t.y]){
mp[t.x][t.y] = 0;
q.push(t);
cnt++;
}
}
}
return cnt;
}
int main(){
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);

Node st;
while (scanf("%d%d", &m, &n), n + m){
for (int i = 0; i < n; i++){
scanf("%s", s);
for (int j = 0; j < m; j++){
mp[i][j] = (s[j] == '#' ? 0 : 1);
if (s[j] == '@')
st.x = i, st.y = j;
}
}
printf("%d\n", bfs(st));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs bfs 搜索