虽然我代码跑的贼慢,但我觉得 还行。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int rows = grid.size();
if(rows == 0)
return 0;
int cols = grid[0].size();
int count = 0;
int xDirection[4] = {-1 , 0 ,1 ,0};
int yDirection[4] = {0 , 1 , 0 , -1};
queue<int> queueA;
set<int> setA;
for( int i = 0 ; i < rows ; i++)
{
for(int j = 0 ; j < cols ; j++)
{
if(grid[i][j] == '1' && (setA.find(i*cols + j) == setA.end()))
{
queueA.push(i);
queueA.push(j);
setA.insert(i*cols + j);
while(!queueA.empty())
{
int x = queueA.front();
queueA.pop();
int y = queueA.front();
queueA.pop();
for(int k = 0 ; k < 4 ; k++)
{
int tempX = x + xDirection[k];
int tempY = y + yDirection[k];
if(tempY < 0 || tempY >= cols || tempX < 0 || tempX >= rows)
continue;
if(grid[tempX][tempY] == '1' && (setA.find(tempX*cols + tempY) == setA.end()))
{
queueA.push(tempX);
queueA.push(tempY);
setA.insert(tempX*cols + tempY);
}
}
}
count++;
}
}
}
return count;
}
};