对于一个01矩阵A,求其中有多少片连成一片的1. 每个1可以和上下左右的1相连.
思路:泛洪(DFS)
class Solution {
public:
void flood(vector<vector<char>>& A, int i, int j, int m, int n) {
if (i < m && i >= 0 && j < n && j >= 0 && A[i][j] == '1') {
A[i][j] = '0';
flood(A, i-1, j, m, n);
flood(A, i+1, j, m, n);
flood(A, i, j-1, m, n);
flood(A, i, j+1, m, n);
}
}
int countConnectedOnes(vector<vector<char>>& A) {
int m = A.size();
if (m == 0) return 0;
int n = A[0].size();
if (n == 0) return 0;
int count = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (A[i][j] == '1') {
count++;
flood(A, i, j, m, n);
}
return count;
}
};