资讯专栏INFORMATION COLUMN

[LeetCode] 947. Most Nodes Removed

Zachary / 521人阅读

Problem

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 <= stones.length <= 1000
0 <= stonesi < 10000

Solution
class Solution {
    public int removeStones(int[][] stones) {
        int m = stones.length;
        int[] parents = new int[m];
        for (int i = 0; i < m; i++) {
            parents[i] = i;
        }
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = i+1; j < m; j++) {
                if (stones[j][0] == stones[i][0] || stones[j][1] == stones[i][1]) {
                    int p1 = find(parents, i);
                    int p2 = find(parents, j);
                    parents[p1] = p2;
                    if (p1 != p2) {
                        count++;
                    }
                }
            }
        }
        return count;
    }
    private int find(int[] parents, int i) {
        if (parents[i] == i) return i;
        else return find(parents, parents[i]);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72531.html

相关文章

  • [LeetCode] 545. Boundary of Binary Tree

    Problem Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate no...

    newtrek 评论0 收藏0
  • LeetCode 545. Boundary of Binary Tree 二叉树边界

    摘要:二叉树边界题意高频题,必须熟练掌握。逆时针打印二叉树边界。解题思路根据观察,我们发现当为左边界时,也是左边界当为左边界时,为空,则也可以左边界。先加入左边,加入,然后得到两个子树加入,最后加入右边界。 LeetCode 545. Boundary of Binary Tree 二叉树边界Given a binary tree, return the values of its boun...

    Astrian 评论0 收藏0
  • [LeetCode] 429. N-ary Tree Level Order Traversal (

    429. N-ary Tree Level Order Traversal Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example, given a 3-ary tree:showImg(https...

    LiangJ 评论0 收藏0
  • [LeetCode] 684. Redundant Connection

    Problem In this problem, a tree is an undirected graph that is connected and has no cycles. The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one...

    lncwwn 评论0 收藏0

发表评论

0条评论

Zachary

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<