- Number of Islands II
Given a n,m which means the row and column of the 2D matrix and an array of pair A( size k). Originally, the 2D matrix is all 0 which means there is only sea in the matrix. The list pair has k operator and each operator has two integer A[i].x, A[i].y means that you can change the grid matrix[A[i].x][A[i].y] from sea to island. Return how many island are there in the matrix after each operator.
Example
Given n = 3, m = 3, array of pair A = [(0,0),(0,1),(2,2),(2,1)].
return [1,1,2,2].
Notice
0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
解法1:
这题也是可以用并查集的经典题。但比前面的几道并查集题要难一些。
要点:
1)记得将二维表降维成一维,即(i,j)=i*nCol + j,这样就跟一维的情况一样了。
2) 在add()里面,因为最开始的点(x,y)在4个方向的循环中,可能已经跟前面方向的并了,所以find(x,y)的值也变了,所以find(x,y)必须在每次循环中都更新,而不能add()一开始就保存下来。
3) 在add()里面,如果是重复点直接返回之前的count。
代码如下:
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
/**
* @param n: An integer
* @param m: An integer
* @param operators: an array of point
* @return: an integer array
*/
vector<int> numIslands2(int n, int m, vector<Point> &operators) {
father.resize(n * m);
grid.resize(n * m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int num = i * m + j;
father[num] = num;
grid[num] = 0;
}
}
count = 0; //num of islands
int numOperators = operators.size();
for (int i = 0; i < numOperators; ++i) {
add(operators[i].x, operators[i].y);
}
return result;
}
private:
// left, down, right, up
// x is index of row, y is index of col
vector<int> dx = {0, -1, 0, 1};
vector<int> dy = {-1, 0, 1, 0};
//find root
int find(int x, int y) {
int num = x * nCol + y;
int num2 = num;
if (father[num] == num) return num;
int origX = x, origY = y;
while (father[num] != num) {
num = father[num];
}
//path compression
while(father[num2] != num) {
int temp = father[num2];
father[num2] = num;
num2 = temp;
}
return num;
}
void add(int x, int y) {
//do not add duplicate node
if (grid[x * nCol + y] == 1) {
result.push_back(count);
return;
}
grid[x * nCol + y] = 1;
int rootA, rootB;
count++;
for (int i = 0; i < 4; ++i) {
int newX = x + dx[i]; // new row index
int newY = y + dy[i]; // new col index
if ((newX >= 0 ) && (newX < nRow) && (newY >= 0) && (newY < nCol)) {
int num = newX * nCol+ newY;
if (grid[num]) {
rootA = find(x, y); //note! each time it needs to recalculate!
rootB = find(newX, newY);
if (rootA != rootB) {
father[rootA] = rootB;
count--;
}
}
}
}
result.push_back(count);
}
vector<int> father;
vector<int> grid;
vector<int> result;
int count;
int nRow;
int nCol;
};
解法2:
DFS。下次做。