BFS 求給定的矩陣中「塊」的個數

2021-10-20 06:56:53 字數 1336 閱讀 1159

給出乙個 m×n 的矩陣,矩陣中的元素為 0 或 1。稱位置 (x, y) 與其上、下、左、右四個位置是相鄰的。如果矩陣中有若干個 1 是相鄰的(不必考慮兩兩相鄰),那麼稱這些 1 構成了乙個「塊」。求給定矩陣中「塊」的個數。

4
思路:

對於矩陣 matrix[m][n] 遍歷每個元素,如果為0,則跳過;如果為 1 ,則使用bfs查詢與該位置相鄰的4個位置(前提是不出界),判斷它們是否為 1(如果相鄰的位置為1,則同樣去查詢與該位置相鄰的4個位置,直到整個「1」塊訪問完畢)。為了防止走回頭路,設定乙個 bool型的 inq陣列記錄 每個元素是否已被訪問過(在bfs中入隊)。

技巧:

int x = ; // 上下左右

int y = ;

code::

#include #include #include using namespace std;

const int maxn = 100; //二維陣列的最大行列數

int n, m; // n:矩陣行數,m矩陣列數

int matrix[maxn][maxn];

bool inq[maxn][maxn] = ; // 設定所有元素為未訪問過

struct node node; //充當臨時變數,入隊出隊時候用

int x[4] = ; // 增量陣列,該位置增加對應值就是 上、下、左、右的位置下標

int y[4] = ;

bool judge(int x, int y)

void bfs(int x, int y) }}

}int main()

}//依次遍歷矩陣的每個元素,如果為1,增加乙個塊,並bfs廣度遍歷它相鄰的元素,設定為已訪問過,以防其他塊搶

int ans = 0;

for (int i = 0; i < n; i++) }}

printf("%d\n", ans);

return 0;

}

BFS寬搜模板(求矩陣中連通塊的個數)

給出乙個n m的矩陣,元素為0或1.稱每個位置的上下左右與之相鄰。如果矩陣中有若干個1是相鄰的,那麼這些1就構成了乙個塊。求矩陣中 塊 的個數。include include include include include include using namespace std typedef lo...

Algorithm 矩陣中「塊」的個數

以下分別給出dfs和bfs實現方法 include include using namespace std define maxn 1000 define ptf printf n define here a,b printf here here here d,d n a,b int n,m,num...

BFS識別矩陣中的塊數

題目描述 給出乙個m n的矩陣,矩陣中的元素為0或1.稱位置 x,y 與其上下左右四個位置是相鄰的。如果矩陣中有若干個1相鄰,則稱這些1構成了乙個塊。求給定矩陣中的塊數。輸入 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 ...