LeetCode 1791: Find Center of Star Graph
Problem Description
Explanation:
To find the center of the star graph, we can observe that the center node will always be connected to every other node in the graph. Therefore, the node that appears in all the edges will be the center of the star graph. We can count the occurrences of each node in the given edges and return the node that appears n-1 times. :
Solutions
class Solution {
public int findCenter(int[][] edges) {
int n = edges.length + 1;
int[] count = new int[n + 1];
for (int i = 0; i < edges.length; i++) {
count[edges[i][0]]++;
count[edges[i][1]]++;
}
for (int i = 1; i <= n; i++) {
if (count[i] == n - 1) {
return i;
}
}
return -1;
}
}
Loading editor...