boolean efficientRoadNetwork(int n, int[][] roads) {
if(roads.length == 0 && n == 1){
return true;
}
// default everything is false
boolean[][] matrix = new boolean[n][n];
for(int i = 0;i < roads.length;i++){
matrix[roads[i][0]][roads[i][1]] = true;
matrix[roads[i][1]][roads[i][0]] = true;
}
int cities = 0;
// if n is 6 we stop at 5
while(cities < n){
int count = 0;
boolean[] visited = new boolean[n];
for(int i = 0; i < matrix.length; i++){
// look for edges at current city
if(matrix[cities][i]){
visited[i] = true;
// check for edges from current edge
for(int j = 0; j < matrix.length; j++){
if(j == i){
continue;
}
if(matrix[i][j]){
visited[j] = true;
}
}
}
}
// each city should have n edges
for(int i = 0; i < visited.length;i++){
if(!visited[i]){
return false;
}
}
// move to next city
cities++;
}
return true;
}
/*
*
*
[
[3, 0],
[0, 4],
[5, 0],
[2, 1],
[1, 4],
[2, 3],
[5, 2]
]
*
*
*/
int [] getChildren(int s, int[][] roads, int p){
List<Integer> children = new ArrayList<>();
for(int i = 0; i < roads.length; i++){
if(roads[i][0] == s && roads[i][1] != p){
children.add(roads[i][1]);
}
if(roads[i][1] == s && roads[i][0] != p){
children.add(roads[i][0]);
}
}
return children
.stream()
.mapToInt(Integer::intValue)
.toArray();
}
boolean efficientRoadNetwork(int n, int[][] roads) {
// 0 to n
for(int i = 0; i < n; i++){
int total = 0;
int[] children = getChildren(i, roads, -1);
System.out.println("children");
// this is a one level tree
if(children.length + 1 == n){
return true;
}
total += children.length;
Arrays.stream(children).forEach(System.out::println);
// check second level only
for(int j = 0; j < children.length; j++){
int[] innerChildren = getChildren(children[j],roads,i);
System.out.println("inner children");
total += innerChildren.length;
}
if(total < n - 1){
return false;
}
}
return true;
}