您能提供一些指导,让我了解如何通过某种模式在图形中进行搜索。
我有一些具有唯一ID的单向图,它的类型是A,B,C。
我需要根据模式搜索所有ID。例如
如果节点类型按此方向连接,搜索(A
,B
,C
)应该返回所有ID。返回值可能为[1,4,6]
[4,6,8]
,依此类推。
当我查看某些特定类型的节点时,Bfs和dfs可能会有所帮助,但是如果我有一个模式在这些节点之间建立连接,我该如何搜索呢?
我的测试如下:
Vertex<Integer, String> vertex1 = new Vertex<Integer, String>(1, "A");
Vertex<Integer, String> vertex2 = new Vertex<Integer, String>(2, "B");
Vertex<Integer, String> vertex3 = new Vertex<Integer, String>(3, "D");
Vertex<Integer, String> vertex4 = new Vertex<Integer, String>(4, "A");
Vertex<Integer, String> vertex5 = new Vertex<Integer, String>(5, "C");
Vertex<Integer, String> vertex6 = new Vertex<Integer, String>(6, "B");
Vertex<Integer, String> vertex7 = new Vertex<Integer, String>(7, "E");
Vertex<Integer, String> vertex8 = new Vertex<Integer, String>(8, "C");
vertex1.setNeighbors(Collections.singletonList(vertex2));
vertex2.setNeighbors(Arrays.asList(vertex3, vertex5));
vertex3.setNeighbors(Collections.singletonList(vertex2));
vertex4.setNeighbors(Arrays.asList(vertex5, vertex6, vertex7));
vertex5.setNeighbors(Arrays.asList(vertex2, vertex4, vertex6));
// vertex5.setNeighbors(Arrays.asList(vertex2, vertex3, vertex4, vertex6));
vertex6.setNeighbors(Arrays.asList(vertex4, vertex5, vertex8));
vertex7.setNeighbors(Collections.singletonList(vertex4));
vertex8.setNeighbors(Collections.singletonList(vertex6));
List<List<String>> expectedAnswers = new ArrayList<List<String>>();
List<String> answer = new ArrayList<String>();
answer.add("1");
answer.add("2");
answer.add("5");
expectedAnswers.add(answer);
answer = new ArrayList<String>();
answer.add("4");
answer.add("6");
answer.add("5");
expectedAnswers.add(answer);
answer = new ArrayList<String>();
answer.add("4");
answer.add("6");
answer.add("8");
expectedAnswers.add(answer);
List<String> typePattern = new ArrayList<String>();
typePattern.add("A");
typePattern.add("B");
typePattern.add("C");
// typePattern.add("D");
Graph<Integer, String> graph = new Graph<Integer, String>();
List<List<String>> resutls = graph.search(vertex1, typePattern);
assertResults(resutls, expectedAnswers);
答案 0 :(得分:1)
以您的示例为例: