LeetCode Solutions

947. Most Stones Removed with Same Row or Column

Time: $O(n^2)$

Space: $O(n)$

			

class Solution {
 public:
  int removeStones(vector<vector<int>>& stones) {
    int numOfIslands = 0;
    vector<vector<int>> graph(stones.size());
    unordered_set<int> seen;

    for (int i = 0; i < stones.size(); ++i)
      for (int j = i + 1; j < stones.size(); ++j)
        if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
          graph[i].push_back(j);
          graph[j].push_back(i);
        }

    for (int i = 0; i < stones.size(); ++i)
      if (seen.insert(i).second) {
        dfs(graph, i, seen);
        ++numOfIslands;
      }

    return stones.size() - numOfIslands;
  }

 private:
  void dfs(const vector<vector<int>>& graph, int u, unordered_set<int>& seen) {
    for (const int v : graph[u])
      if (seen.insert(v).second)
        dfs(graph, v, seen);
  }
};
			

class Solution {
  public int removeStones(int[][] stones) {
    int numOfIslands = 0;
    List<Integer>[] graph = new List[stones.length];
    Set<Integer> seen = new HashSet<>();

    for (int i = 0; i < graph.length; ++i)
      graph[i] = new ArrayList<>();

    for (int i = 0; i < stones.length; ++i)
      for (int j = i + 1; j < stones.length; ++j)
        if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
          graph[i].add(j);
          graph[j].add(i);
        }

    for (int i = 0; i < stones.length; ++i)
      if (seen.add(i)) {
        dfs(graph, i, seen);
        ++numOfIslands;
      }

    return stones.length - numOfIslands;
  }

  private void dfs(List<Integer>[] graph, int u, Set<Integer> seen) {
    for (final int v : graph[u])
      if (seen.add(v))
        dfs(graph, v, seen);
  }
}