LeetCode //C - 547. Number of Provinces

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

Constraints:
  • 1 <= n <= 200
  • n == isConnected.length
  • n == isConnected[i].length
  • isConnected[i][j] is 1 or 0.
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

From: LeetCode
Link: 547. Number of Provinces


Solution:

Ideas:

1. Function Definition: findCircleNum is the function that takes in the adjacency matrix (isConnected), its size (isConnectedSize), and a pointer to an array representing the size of each row (isConnectedColSize).

2. Visited Array: We create an array called visited to keep track of which cities have been visited during the DFS. This array has one entry per city, initialized to 0 (indicating no cities have been visited at the start).

3. DFS Function: The dfs function is a recursive function that marks the current city as visited and then looks for all cities directly connected to it that have not yet been visited. It calls itself recursively for each unvisited city, effectively traversing the entire province.

4. Counting Provinces: In the findCircleNum function, we iterate over each city. If a city hasn’t been visited yet, we call the dfs function on it, which will visit all cities in its province. Once we return from the dfs call, we know we’ve fully visited one province, so we increment our province count.

5. Main Function: The main function is just an example of how to use findCircleNum. It creates an adjacency matrix for a set of cities, calls the findCircleNum function to find the number of provinces, and then frees the allocated memory.

Code:
void dfs(int** isConnected, int isConnectedSize, int* visited, int i) {
    for (int j = 0; j < isConnectedSize; j++) {
        if (isConnected[i][j] == 1 && !visited[j]) {
            visited[j] = 1;
            dfs(isConnected, isConnectedSize, visited, j);
        }
    }
}

int findCircleNum(int** isConnected, int isConnectedSize, int* isConnectedColSize) {
    int provinces = 0;
    int *visited = (int *)calloc(isConnectedSize, sizeof(int));

    for (int i = 0; i < isConnectedSize; i++) {
        if (!visited[i]) {
            dfs(isConnected, isConnectedSize, visited, i);
            provinces++;
        }
    }

    free(visited);
    return provinces;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,深度优先,算法)