赞
踩
对于蓝色的小块而言,四联通块(题目不说一般都是四联通)就是周围红色的区域,是可到达的位置,八联通块是加上黄色的位置
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 110;
-
- int n, m, a[maxn][maxn];
-
-
- int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
- bool vis[maxn][maxn];
-
- void dfs(int x, int y) {
- if (x < 1 || y < 1 || x > n || y > n)
- return ;
- if (vis[x][y])
- return ;
- vis[x][y] = 1;
- for (int i = 0; i < 4; i ++) {
- int nx = x + dx[i], ny = y + dy[i];
- dfs(nx, ny);
- }
-
- }
-
- int main() {
- cin >> n >> m;
- for (int i = 1; i <= n; i ++)
- for (int j = 1; j <= m; j ++)
- cin >> a[i][j];
- int cnt = 0;
- for (int i = 1; i <= n; i ++)
- for (int j = 1; j <= m; j ++)
- if (!vis[i][j])
- cnt ++, dfs(i, j);
- cout << cnt;
- return 0;
- }
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 110;
-
- int n, m, a[maxn][maxn];
-
-
-
- int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
- bool vis[maxn][maxn];
-
- struct node {
- int x, y;
- };
-
- void bfs(int x, int y) {
- queue<node> q;
- q.push((node) {
- x, y
- }) ;
- while (!q.empty()) {
- node t = q.front();
- q.pop();
- if (t.x < 1 || t.x > n || t.y > m || t.y < 1)
- continue;
- if (vis[t.x][t.y])
- continue;
- vis[t.x][t.y] = 1;
- for (int i = 0; i <= 4; i ++) {
- int nx = t.x + dx[i], ny = t.y + dy[i];
- q.push((node) {
- nx, ny
- });
- }
- }
- }
-
- int main() {
- cin >> n >> m;
- for (int i = 1; i <= n; i ++)
- for (int j = 1; j <= m; j ++)
- cin >> a[i][j];
- int cnt = 0;
- for (int i = 1; i <= n; i ++)
- for (int j = 1; j <= m; j ++)
- if (!vis[i][j])
- cnt ++, bfs(i, j);
- cout << cnt;
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。