1. 程式人生 > >【leetcode】947. Most Stones Removed with Same Row or Column

【leetcode】947. 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

解題思路:題目解法本身不難,難點在於包了一個殼,去掉殼後就能看到本質了。本題的殼就是分組,把所有行相同或者列相同的元素分進同一個組,計算出一個有多少個組,刪除操作完成後,每個組都會留下一個元素。最後的結果就是stones的個數減去組的個數。至於怎麼求組的個數,DFS或者並查集都是可行的方法。我的解法是用DFS,最初用的是visit陣列來儲存元素是否遍歷過,但是python語言會超時,只好改成每遍歷完一個元素,都將其從stones中刪除。

程式碼如下:

class Solution(object):
    def removeStones(self, stones):
        
""" :type stones: List[List[int]] :rtype: int """ group = 0 original_len = len(stones) while len(stones) > 0: group += 1 queue = [(stones[0][0],stones[0][1])] del stones[0] while len(queue) > 0: r, c = queue.pop(0) inx_internal = 0 while inx_internal < len(stones): if r == stones[inx_internal][0] or c == stones[inx_internal][1]: queue.append((stones[inx_internal][0], stones[inx_internal][1])) del stones[inx_internal] else: inx_internal += 1 return original_len - group