我正在努力学习更多关于网络图搜索算法的知识.为了说明这一点,我创建了以下示例.
假设有Step 1:个国家(COUNTRY_1...COUNTRY_Step 1:)彼此随机连接
set.seed(123)
library(igraph)
countries <- paste0("country_", 1:100)
g <- make_empty_graph(100)
num_edges <- 200
edge_list <- sample(countries, size = num_edges * 2, replace = TRUE)
edge_list <- matrix(edge_list, ncol = 2, byrow = TRUE)
g <- graph_from_edgelist(edge_list, directed = FALSE)
V(g)$name <- countries
plot(g, vertex.label.cex = 0.7, vertex.label.color = "black", vertex.label.dist = 2)
Step 2:现在,假设20个人(Person_A...Person_T)生活在这些国家(每个国家最多只能有一个人--其中80个国家将是空的):
edge_list <- as_edgelist(g)
df <- as.data.frame(edge_list)
colnames(df) <- c("from", "to")
people <- paste0("person_", LETTERS[1:20])
assignment <- sample(countries, size = length(people), replace = FALSE)
names(assignment) <- people
df2 <- data.frame(country = countries)
df2$person <- ifelse(df2$country %in% assignment, names(assignment)[match(df2$country, assignment)], "empty")
Step 3:作为可选步骤,我们可以将结果可视化:
library(visNetwork)
df2$color <- ifelse(df2$person == "empty", "grey", "red")
df2$label <- ifelse(df2$person == "empty", df2$country, paste0(df2$person, "\n", df2$country))
nodes <- data.frame(id = df2$country, label = df2$label, color = df2$color)
edges <- df
visNetwork(nodes, edges) %>%
visInteraction(navigationButtons = TRUE)
假设我们以"Person_A"为例--我想找出谁离"Person_A"最近,这个人住在哪个国家.I am interested in learning how to write a BFS algorithm for this problem by hand-例如:取Person_A搜索半径为1的所有人--如果没有找到任何人,现在搜索半径为2的所有人...继续下go ,直到你找到第一个人(S).
我知道如何使用此算法的预构建实现:
adj_matrix <- as_adjacency_matrix(g)
diag(adj_matrix) <- 0
shortest_paths <- shortest.paths(g)
df2_filtered <- subset(df2, person != "empty")
selected_countries <- intersect(rownames(shortest_paths), df2_filtered$country)
filtered_paths <- shortest_paths[selected_countries, selected_countries]
item = df2[df2$person %in% c("person_A"), ]
#answer (exclude distance = 0, i.e. the same country itself)
sort(filtered_paths[rownames(filtered_paths) == item$country, ])[2]
Can someone please show me how I could write a search algorithm (by hand) to accomplish this task which starts with a person's name - and then prints the results of the search at each step until a person is found?个