You are on page 1of 3

Samantha Sinnerine

CSCI-313
HW#14

C-14.37

public void removeEdge(Edge<E> e) throws IllegalArgumentException {


InnerEdge<E> edge = validate(e); // Validate the edge

InnerVertex<V> origin = edge.getEndpoints()[0];


InnerVertex<V> destination = edge.getEndpoints()[1];

// Remove the edge from the outgoing edges of the origin vertex
origin.getOutgoing().remove(destination);

// Remove the edge from the incoming edges of the destination vertex
destination.getIncoming().remove(origin);

// Remove the edge from the edges list


edges.remove(edge.getPosition());

// For undirected graphs, remove the reverse edge as well


if (!isDirected) {
// Find the reverse edge
Edge<E> reverseEdge = destination.getOutgoing().get(origin);

// Remove the reverse edge from the outgoing edges of the destination
vertex
destination.getOutgoing().remove(origin);

// Remove the reverse edge from the incoming edges of the origin vertex
origin.getIncoming().remove(destination);

// Remove the reverse edge from the edges list


edges.remove(((InnerEdge<E>) reverseEdge).getPosition());
}
}

-----------------------------------------------------------------------------------
------------------------------------------------------------
C-14.42

public static <V, E> List<Vertex<V>> findCycle(Graph<V, E> graph) {


Set<Vertex<V>> visited = new HashSet<>();
List<Vertex<V>> cycle = new ArrayList<>();

for (Vertex<V> vertex : graph.vertices()) {


if (!visited.contains(vertex)) {
if (dfs(graph, vertex, visited, cycle)) {
return cycle;
}
}
}

return null; // No cycle found


}
private static <V, E> boolean dfs(Graph<V, E> graph, Vertex<V> current,
Set<Vertex<V>> visited, List<Vertex<V>> cycle) {
visited.add(current);
cycle.add(current);

for (Edge<E> outgoingEdge : graph.outgoingEdges(current)) {


Vertex<V> neighbor = graph.opposite(current, outgoingEdge);

if (cycle.contains(neighbor)) {
// Found a cycle
int index = cycle.indexOf(neighbor);
cycle.subList(0, index).clear(); // Remove the elements before the
cycle start
return true;
}

if (!visited.contains(neighbor) && dfs(graph, neighbor, visited, cycle)) {


return true;
}
}

cycle.remove(current);
return false;
}

-----------------------------------------------------------------------------------
------------------------------------------------------------
C-14.50

import java.util.*;

public class BFS {


public static <V, E> void bfs(Graph<V, E> graph, Vertex<V> start) {
Set<Vertex<V>> visited = new HashSet<>();
Queue<Vertex<V>> queue = new LinkedList<>();

visited.add(start);
queue.offer(start);

while (!queue.isEmpty()) {
Vertex<V> current = queue.poll();
System.out.println(current.getElement()); // Process the vertex (e.g.,
print its element)

for (Edge<E> edge : graph.outgoingEdges(current)) {


Vertex<V> neighbor = graph.opposite(current, edge);

if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.offer(neighbor);
}
}
}
}
}

You might also like