求矩陣塊數(BFS模板)

 給出一個 m x n 的矩陣,矩陣中的元素爲0或1。

    稱位置(x,y)與其上下左右四個位置(x,y+1)、(x,y-1)、(x+1,y)、(x-1,y)是相鄰的。
    
    如果矩陣中有若干個1是相鄰的(不必兩兩相鄰),那麼稱這些1構成了一個“塊”。求給定的矩陣中“塊”的個數。
 

#include <iostream>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <set>
#include <cstdio>
#include <fstream>
#include <deque>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.141592653589793238462643383279;
using namespace std;
const int N = 1e7 + 5;
const int maxn = 1 << 20;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; while (b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
/*void chafen(int l, int r, int k) {//差分函數
    p[l] += k;
    p[r + 1] -= k;
}*/
/*********************************************************/
bool vis[105][105];
int a[105][105]; int n, m;
struct node {
    int x;
    int y;
};
bool test(int x, int y) {
    if (x<0 || x>=n || y<0 || y>=m)
        return false;
    if (a[x][y] == 0 || vis[x][y])
        return false;
    return true;
}
void bfs(int x1, int y1) {
    int x[4] = { -1,0,1,0 };
    int y[4] = { 0,1,0,-1 };
    queue<node> q;
    node p;
    p.x = x1; p.y = y1;
    q.push(p);
    vis[x1][y1] = true;
    while (!q.empty()) {
        node p1 = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int x2 = p1.x + x[i];
            int y2 = p1.y + y[i];
            if (test(x2, y2)) {
                node p2;
                p2.x = x2;
                p2.y = y2;
                q.push(p2);
                vis[x2][y2] = true;
            }
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> a[i][j];
    memset(vis, false, sizeof(vis));
    int ans = 0;
    for(int i=0;i<n;i++)
        for (int j = 0; j < m; j++) {
            if (a[i][j] == 1 && !vis[i][j]) {
                ans++;
                bfs(i, j);
            }
        }
    cout << ans << endl;
    return 0;
}
/*
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
*/

練習BFS&&DFS,自己的搜索太爛了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章