题目链接:HDU 1241
思路: 用BFS DFS。
AC代码:
DFS
#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn];
int n, m;
int X[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int Y[8] = {0, 0, 1, -1, -1, 1, 1, -1};
struct node{
int x, y;
};
bool check(node now){
if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '*'){
return 0;
}
return 1;
}
void DFS(node s){
vis[s.x][s.y] = 1;
node next;
for(int i = 0; i < 8; i ++){
next.x = s.x + X[i];
next.y = s.y + Y[i];
if( check(next) && !vis[next.x][next.y] ){
vis[next.x][next.y] = 1;
DFS(next);
}
}
}
int main(){
while(cin >> n >> m && n + m){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m;j ++){
cin >> maze[i][j];
}
}
memset(vis, 0, sizeof(vis));
int ans = 0;
node temp;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if( !vis[i][j] && maze[i][j] == '@'){
ans ++;
temp.x = i;
temp.y = j;
DFS(temp);
}
}
}
cout << ans << endl;
}
return 0;
}
BFS:
#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn];
int n, m;
int X[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int Y[8] = {0, 0, 1, -1, -1, 1, 1, -1};
struct node{
int x, y;
};
bool check(node now){
if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '*'){
return 0;
}
return 1;
}
int BFS(node s){
queue<node> q;
q.push(s);
vis[s.x][s.y] = 1;
node front, next;
while(!q.empty()){
front = q.front();
q.pop();
for(int i = 0; i < 8; i++){
next.x = front.x + X[i];
next.y = front.y + Y[i];
if(check(next) && vis[next.x][next.y] == 0){
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
}
int main(){
while(cin >> n >> m && n + m){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m;j ++){
cin >> maze[i][j];
}
}
memset(vis, 0, sizeof(vis));
int ans = 0;
node temp;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if( !vis[i][j] && maze[i][j] == '@'){
ans ++;
temp.x = i;
temp.y = j;
BFS(temp);
}
}
}
cout << ans << endl;
}
return 0;
}