zoukankan      html  css  js  c++  java
  • 547. Number of Provinces 省份数量

    There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

    A province is a group of directly or indirectly connected cities and no other cities outside of the group.

    You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

    Return the total number of provinces.

     

    Example 1:

    Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
    Output: 2
    

    Example 2:

    Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
    Output: 3

    和数字岛屿的区别:
    这个例子

    0,0 0,3
    1,1 1,2
    2,1 2,2 2,3
    3,0 3,2 3,3
    0123全都是相通的,所以pyq数量=1。但是岛屿数量是4.

    
    

    您有一个 NxN 矩阵,但总共只有 N 个朋友。所以一行只loop一次就行了。

    
    

    别的特点:本题对角元素全为1。

    教训:题目改名字了,最好重新搜索一下。一定要小心再小心!

    做法是修改一下dfs

    public class Solution {
    
    private int n;
    private int m;
    
    public int numIslands(char[][] grid) {
        int count = 0;
        n = grid.length;
        if (n == 0) return 0;
        m = grid[0].length;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++)
                if (grid[i][j] == '1') {
                    DFSMarking(grid, i, j);
                    ++count;
                }
        }    
        return count;
    }
    
    private void DFSMarking(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return;
        grid[i][j] = '0';
        
        for (int d = 0; d < n; d++)
            dfs(grid, d, j);
    
        for (int d = 0; d < m; d++)
            dfs(grid, i, d);
    }
    }
  • 相关阅读:
    vsftpd的主动模式与被动模式
    Linux环境下vsftpd参数配置
    CentOS下的网络配置文件说明
    第一篇博客,随笔留念
    asp.net xml 增删改操作
    asp.net json 与xml 的基础事例
    linq 之 Distinct的使用
    【P2015】二叉苹果树(树状DP)
    【P2016】战略游戏(贪心||树状DP)
    【P2774】方格取数问题(贪心+最大流,洛谷)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/15570391.html
Copyright © 2011-2022 走看看