1.图顶点和边删除
1.1删除边
@Override public void removeEdge(V from, V to) { Vertex<V, E> fromVertex = vertices.get(from); if (fromVertex == null) return; Vertex<V, E> toVertex = vertices.get(to); if (toVertex == null) return; Edge<V, E> edge = new Edge<>(fromVertex, toVertex); if (fromVertex.outEdges.remove(edge)) { toVertex.inEdges.remove(edge); edges.remove(edge); } }
1.2删除点
@Override public void removeVertex(V v) { Vertex<V, E> vertex = vertices.remove(v); if (vertex == null) return; for (Iterator<Edge<V, E>> iterator = vertex.outEdges.iterator(); iterator.hasNext();) { Edge<V, E> edge = iterator.next(); edge.to.inEdges.remove(edge); // 将当前遍历到的元素edge从集合vertex.outEdges中删掉 iterator.remove(); edges.remove(edge); } for (Iterator<Edge<V, E>> iterator = vertex.inEdges.iterator(); iterator.hasNext();) { Edge<V, E> edge = iterator.next(); edge.from.outEdges.remove(edge); // 将当前遍历到的元素edge从集合vertex.inEdges中删掉 iterator.remove(); edges.remove(edge); } }
2.图的遍历
2.1常见方式
2.2广度优先搜索(Breadth First Search)
2.3广度优先搜索--思路
2.4广度优先搜索-实现
@Override public void bfs(V begin, VertexVisitor<V> visitor) { if (visitor == null) return; Vertex<V, E> beginVertex = vertices.get(begin); if (beginVertex == null) return; Set<Vertex<V, E>> visitedVertices = new HashSet<>(); Queue<Vertex<V, E>> queue = new LinkedList<>(); queue.offer(beginVertex); visitedVertices.add(beginVertex); while (!queue.isEmpty()) { Vertex<V, E> vertex = queue.poll(); if (visitor.visit(vertex.value)) return; for (Edge<V, E> edge : vertex.outEdges) { if (visitedVertices.contains(edge.to)) continue; queue.offer(edge.to); visitedVertices.add(edge.to); } } }
2.5深度优先搜索(Depth First Search)
2.6深度优先递归实现
@Override public void dfs(V begin, VertexVisitor<V> visitor) { if (visitor == null) return; Vertex<V, E> beginVertex = vertices.get(begin); if (beginVertex == null) return; Set<Vertex<V, E>> visitedVertices = new HashSet<>(); Stack<Vertex<V, E>> stack = new Stack<>(); // 先访问起点 stack.push(beginVertex); visitedVertices.add(beginVertex); if (visitor.visit(begin)) return; while (!stack.isEmpty()) { Vertex<V, E> vertex = stack.pop(); for (Edge<V, E> edge : vertex.outEdges) { if (visitedVertices.contains(edge.to)) continue; stack.push(edge.from); stack.push(edge.to); visitedVertices.add(edge.to); if (visitor.visit(edge.to.value)) return; break; } } }
2.7 深度优先搜索--非递归版本
@Override public void dfs(V begin, VertexVisitor<V> visitor) { if (visitor == null) return; Vertex<V, E> beginVertex = vertices.get(begin); if (beginVertex == null) return; Set<Vertex<V, E>> visitedVertices = new HashSet<>(); Stack<Vertex<V, E>> stack = new Stack<>(); // 先访问起点 stack.push(beginVertex); visitedVertices.add(beginVertex); if (visitor.visit(begin)) return; while (!stack.isEmpty()) { Vertex<V, E> vertex = stack.pop(); for (Edge<V, E> edge : vertex.outEdges) { if (visitedVertices.contains(edge.to)) continue; stack.push(edge.from); stack.push(edge.to); visitedVertices.add(edge.to); if (visitor.visit(edge.to.value)) return; break; } } }