|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone. |
| 4 | +
|
| 5 | +Now, a move consists of removing a stone that shares a column or row with another stone on the grid. |
| 6 | +
|
| 7 | +What is the largest possible number of moves we can make? |
| 8 | +
|
| 9 | +
|
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] |
| 14 | +Output: 5 |
| 15 | +Example 2: |
| 16 | +
|
| 17 | +Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] |
| 18 | +Output: 3 |
| 19 | +Example 3: |
| 20 | +
|
| 21 | +Input: stones = [[0,0]] |
| 22 | +Output: 0 |
| 23 | +
|
| 24 | +
|
| 25 | +Note: |
| 26 | +
|
| 27 | +1 <= stones.length <= 1000 |
| 28 | +0 <= stones[i][j] < 10000 |
| 29 | +""" |
| 30 | +from typing import List |
| 31 | +from collections import defaultdict |
| 32 | + |
| 33 | + |
| 34 | +class Solution: |
| 35 | + def removeStones(self, stones: List[List[int]]) -> int: |
| 36 | + """ |
| 37 | + convert to graph problem |
| 38 | + each component in the graph can be removed to only one node |
| 39 | + N - #component |
| 40 | +
|
| 41 | + construct graph O(N^2) |
| 42 | + DFS - O(N) |
| 43 | + """ |
| 44 | + G = defaultdict(list) |
| 45 | + n = len(stones) |
| 46 | + for i in range(n): |
| 47 | + for j in range(i): |
| 48 | + if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]: |
| 49 | + G[i].append(j) |
| 50 | + G[j].append(i) |
| 51 | + |
| 52 | + # dfs |
| 53 | + comp_cnt = 0 |
| 54 | + visited = [False for _ in range(n)] |
| 55 | + for i in range(n): |
| 56 | + if not visited[i]: |
| 57 | + comp_cnt += 1 |
| 58 | + self.dfs(G, i, visited) |
| 59 | + |
| 60 | + return n - comp_cnt |
| 61 | + |
| 62 | + def dfs(self, G, i, visited): |
| 63 | + visited[i] = True |
| 64 | + for nbr in G[i]: |
| 65 | + if not visited[nbr]: |
| 66 | + self.dfs(G, nbr, visited) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + assert Solution().removeStones([[0,0],[0,2],[1,1],[2,0],[2,2]]) == 3 |
0 commit comments