class Solution {
public:
int countConnectedOnes(vector<vector<char>>& A) {
if (A.empty())
return 0;
queue<pair<int,int>>temp;
int count = 0; //计数器
for (int i = 0; i < A.size(); i++)
{
for (int j = 0; j < A[i].size(); j++)
{
if (A[i][j] == '1')
{
temp.push(make_pair(i,j));
while (!temp.empty())
{
int row = temp.front().first;
int col = temp.front().second;
if (A[row][col] == '0')
temp.pop();
else
{
A[row][col] = '0';
temp.pop();
if (row + 1<A.size() && A[row + 1][col] == '1')
temp.push(make_pair(row + 1, col));
if (col + 1<A[row].size() && A[row][col + 1] == '1')
temp.push(make_pair(row, col + 1));
if (col - 1 >= 0 && A[row][col - 1] == '1')
temp.push(make_pair(row, col - 1));
if (row - 1 >= 0 && A[row - 1][col] == '1')
temp.push(make_pair(row - 1, col));
}
}
count++;
}
}
}
return count;
}
};
1003.相连的1
最新推荐文章于 2024-09-12 19:02:20 发布