• 【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
  • 相关阅读:
    解决SecureCRT中文显示乱码
    能大大提升工作效率和时间效率的9个重要习惯
    PHP基础知识
    CI学习相关地址
    IE8引入JavaScript
    IE9以下不支持placeholder属性
    IE8浏览器兼容性问题
    简单的DOS命令
    Linux常用运维指令
    log4j日志+面向切面监控异常
  • 原文地址:https://www.cnblogs.com/seyjs/p/10021220.html
Copyright © 2020-2023  润新知