[C language] brush LeetCode 547. Circle of friends (M)

There are students in the class N. Some of them are friends, some are not. Their friendship has is transitive. If you know a friend B of A, B C is a friend, so we can assume that A is C friend. The so-called circle of friends, is the set of all your friends.

Given an N * N matrix M, represents the friendship between classes high school students. If M [i] [j] = 1, represents a known i-th and j-th student mutual friendship, otherwise I do not know. You must be exported to all students in the total number of known circle of friends.

Example 1:

Enter: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2 
Description: Known students and students 0 1 mutual friends, they are in a circle of friends.
The first two students themselves in a circle of friends. 2 is returned.
Example 2:

Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Description: known Student Student 0 and 1 mutual friend, a student and the student 2 mutually friends, so students and students 0 2 is also a friend, so three of them in a circle of friends, returns 1.
note:

N within the [1,200] range.
For all students, M [i] [i] = 1.
If M [i] [j] = 1, then there are M [j] [i] = 1.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/friend-circles
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

This question and 200. The number of islands (M) is substantially the same, but it will little difference, the code comparison, quite interesting. The problem is within 200 double for dfs, this problem is inside for dfs, dfs again within the for loop.

void findDfs(int** M, int MSize, int i, int *visit) {
    int j;
    
    if (visit[i] == 1) {
        return; 
    }
    
    visit[i] = 1;

    for (j = 0; j < MSize; j++) {
        if((M[i][j] == 1) && (visit[j] == 0)) {
            findDfs(M, MSize, j, visit);
        }
    }
}

int findCircleNum(int** M, int MSize, int* MColSize){
    int i, j;
    int visit[MSize];
    int ret = 0;
    
    memset(visit, 0, sizeof(int) * MSize);
    
    for (i = 0; i < MSize; i++) {
        if (visit[i] == 1) {
            continue; 
        }
        
        findDfs(M, MSize, i, visit);
        
        ret++;
    }
    
    return ret;
}

 

Published 149 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/jin615567975/article/details/104416966