CSci 280: Algorithms and problem-solving paradigms
Home Syllabus Classwork

printable version

Quiz 2

[1] [2] [3] [4] [5] [6]

Problem Q2.1.

[8 pts] The below method takes an undirected graph as a parameter and returns the vertex with the most neighbors-of-neighbors. The UndirectedGraph class is the same as on Assignment 2; all instance methods on it take O(1) time.

Using m to represent the number of edges in the graph and n to represent the number of vertices, what is the running time of the method? Use big-O notation, giving the tightest and simplest bound you can, and justify your answer.

public static <V> V countNeighborsOfNeighbors(UndirectedGraph<V> g) {
    V bestVertex = null;
    int bestCount = -1;
    for(int i = 0; i < g.getVertexCount(); i++) {
        V a = g.getVertex(i);
        HashSet<V> neighbneighb = new HashSet<V>();
        for(V b : g.getNeighbors(a)) {
            for(V c : g.getNeighbors(b)) neighbneighb.add(c);
        }
        if(neighbneighb.size() > bestCount) {
            bestVertex = a;
            bestCount = neighbneighb.size();
        }
    }
    return bestVertex;
}