1. 程式人生 > >[Swift Weekly Contest 112]LeetCode947. 移除最多的同行或同列石頭 | Most Stones Removed with Same Row or Column

[Swift Weekly Contest 112]LeetCode947. 移除最多的同行或同列石頭 | Most Stones Removed with Same Row or Column

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. 1 <= stones.length <= 1000
  2. 0 <= stones[i][j] < 10000

在二維平面上,我們將石頭放置在一些整數座標點上。每個座標點上最多隻能有一塊石頭。

現在,move

 操作將會移除與網格上的另一塊石頭共享一列或一行的石頭。

我們最多能執行多少次 move 操作?

示例 1:

輸入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
輸出:5

示例 2:

輸入:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
輸出:3

示例 3:

輸入:stones = [[0,0]]
輸出:0

提示:

  1. 1 <= stones.length <= 1000
  2. 0 <= stones[i][j] < 10000

1436ms

 1 class Solution {
 2     func removeStones(_ stones: [[Int]]) -> Int {
 3         var n:Int = stones.count
 4         var ds:DJSet = DJSet(n)
 5         for i in 0..<n
 6         {
 7             for j in (i + 1)..<n
 8             {
 9                 if stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]
10                 {
11                     ds.union(i, j)
12                 }
13             }
14         }
15         return n-ds.count()
16     }
17 }
18 
19 public class DJSet 
20 {
21     var upper:[Int] = [Int]()
22     
23     public init(_ n:Int)
24     {
25         upper = [Int](repeating:-1,count: n)
26     }
27     
28     public func root(_ x:Int) -> Int
29     {
30         if upper[x] < 0
31         {
32             return x
33         }
34         else
35         {
36             upper[x] = root(upper[x])
37             return upper[x]
38         }
39     }
40     
41     public func equiv(_ x:Int,_ y:Int) -> Bool
42     {
43         return root(x) == root(y)
44     }
45     
46     public func union(_ x:Int,_ y:Int) -> Bool
47     {
48         var x:Int = root(x)
49         var y:Int = root(y)
50         if (x != y)
51         {
52             if (upper[y] < upper[x]) 
53             {
54                 var d:Int = x
55                 x = y
56                 y = d
57             }
58             upper[x] += upper[y]
59             upper[y] = x
60         }
61         return x == y
62     }
63 
64     public func count()-> Int 
65     {
66         var ct:Int = 0
67         for u in upper
68         {
69             if u < 0
70             {
71                 ct += 1
72             }
73         }
74         return ct
75     }
76 }