On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3:
Input: stones = [[0,0]]
Output: 0
Note:
1 <= stones.length <= 1000
0 <= stones[i][j] < 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
1、半天读不懂题意系列,可以移动横坐标或纵坐标相同的石头。也就是当他们横坐标或纵坐标相同时,是连通的。连通的就可以一个一个接着取掉。
2、所以dfs思路就是:找到连通分量,用石子数量-连通分量就是可以remove的个数
class Solution {
public:
int removeStones(vector<vector<int>>& stones) {
vector<bool> vis(stones.size(), false);
int count = 0;
for(int i = 0; i < stones.size(); i++){
if(!vis[i]){
dfs(i,{stones[i][0], stones[i][1]}, vis, stones);
count++;
}
}
return stones.size() - count;
}
void dfs(int idx, pair<int, int> p, vector<bool>& vis, vector<vector<int>>& stones){
vis[idx] = true;
for(int i = 0; i < stones.size(); i++){
int x = stones[i][0], y = stones[i][1];
if((p.first == x || p.second == y)&&!vis[i]){
vis[i] = true;
dfs(i,{x,y},vis,stones);
}
}
}
};