标签:clu dfs namespace any family VID mit iss angular
本题是指@表示油点,*表示非油点,油点相邻则表示一个油点而不是多个,找出总油点个数。没啥技巧,就是八个方向搜索,同时利用并查集的效率更高
DFS搜索:
#include <iostream>
#include <cstring>
using namespace std;
int m,n,many;
char s[105][105];
int visit[105][105];
const int dx[] = {0,0,1,1,1,-1,-1,-1};
const int dy[] = {1,-1,0,1,-1,0,1,-1};
void dfs(int i, int j){
visit[i][j] = 1;
for(int k = 0; k < 8; k++)
{
int nx = i + dx[k];
int ny = j + dy[k];
if(nx >= 0 && nx < m && ny >= 0 && ny < n && visit[nx][ny] == 0 && s[nx][ny] == ‘@‘)
dfs(nx,ny);
}
//return 1;
}
int main(){
while(cin >> m >> n)
{
many = 0;
memset(s, 0, sizeof(s));
memset(visit,0,sizeof(visit));
if(m == 0)
break;
for(int i = 0; i < m; i++){
cin >> s[i];
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(s[i][j] == ‘@‘ && visit[i][j] == 0)
{
many++;
dfs(i, j);
}
}
}
cout << many << endl;
}
return 0;
}
并查集:
#include<bits/stdc++.h>
using namespace std;
char g[101][101];
int fa[101 * 101];
int x[] = { 0,0,1,-1,1,-1,1,-1 };
int y[] = { 1,-1,0,0,1,1,-1,-1 };
int n, m;
int id(int x, int y) {
return (x - 1)*m + y;
}
bool isok(int x, int y) {
if (0 < x&&x <= n && 0 < y&&y <= m)
return true;
return false;
}
int Find(int x) {
return fa[x] == x ? x : fa[x] = Find(fa[x]);
}
int vis[101 * 101];
int main() {
while (scanf("%d%d", &n, &m) != EOF && n + m) {
memset(vis, 0, sizeof vis);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
fa[id(i, j)] = id(i, j);
}
}
for (int i = 1; i <= n; ++i)
scanf("%s", g[i] + 1);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (g[i][j] == ‘*‘) continue;
for (int k = 0; k < 7; ++k) {
int xx = i + x[k], yy = j + y[k];
if (isok(xx, yy) == false || g[xx][yy] == ‘*‘) continue;
int f1 = Find(id(i, j)), f2 = Find(id(xx, yy));
if (f1 != f2) {
fa[f1] = f2;
}
}
}
}
int cnt = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (g[i][j] != ‘*‘&&vis[Find(id(i, j))] == 0) {
cnt++;
vis[Find(id(i, j))] = 1;
}
}
}
cout << cnt << endl;
}
return 0;
}
#1241: Oil Deposits(八向搜索 + 并查集)
标签:clu dfs namespace any family VID mit iss angular
原文地址:https://www.cnblogs.com/RioTian/p/12858317.html