栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何获得迷宫中最短的路线?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何获得迷宫中最短的路线?

您可以构造一个图形来表示矩阵中位置之间的有效移动:

# Construct nodes and edges from matrix(nodes <- which(m == 1 | m == 2 | m == 3, arr.ind=TRUE))#       row col#  [1,]   1   1#  [2,]   2   1#  [3,]   4   1#  [4,]   2   2#  [5,]   3   2#  [6,]   4   2#  [7,]   4   3#  [8,]   2   4#  [9,]   4   4edges <- which(outer(seq_len(nrow(nodes)),seq_len(nrow(nodes)), function(x, y) abs(nodes[x,"row"] - nodes[y,"row"]) + abs(nodes[x,"col"] - nodes[y,"col"]) == 1), arr.ind=T)(edges <- edges[edges[,"col"] > edges[,"row"],])#      row col# [1,]   1   2# [2,]   2   4# [3,]   4   5# [4,]   3   6# [5,]   5   6# [6,]   6   7# [7,]   7   9library(igraph)g <- graph.data.frame(edges, directed=FALSE, vertices=seq_len(nrow(nodes)))

然后,您可以解决指定起点和终点之间的最短路径问题:

start.pos <- which(m == 2, arr.ind=TRUE)start.node <- which(paste(nodes[,"row"], nodes[,"col"]) == paste(start.pos[,"row"], start.pos[,"col"]))end.pos <- which(m == 3, arr.ind=TRUE)end.node <- which(paste(nodes[,"row"], nodes[,"col"]) == paste(end.pos[,"row"], end.pos[,"col"]))(sp <- nodes[get.shortest.paths(g, start.node, end.node)$vpath[[1]],])#      row col# [1,]   1   1# [2,]   2   1# [3,]   2   2# [4,]   3   2# [5,]   4   2# [6,]   4   3# [7,]   4   4

最后,您可以确定方向(1:东; 2:北; 3:西; 4:南),作为对所选最终节点集的简单操纵:

dx <- diff(sp[,"col"])dy <- -diff(sp[,"row"])(dirs <- ifelse(dx == 1, 1, ifelse(dy == 1, 2, ifelse(dx == -1, 3, 4))))# [1] 4 1 4 4 1 1

此代码适用于任意大小的输入矩阵。

数据:

(m <- matrix(c(2, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 3), nrow=4))#      [,1] [,2] [,3] [,4]# [1,]    2    0    0    0# [2,]    1    1    0    1# [3,]    0    1    0    0# [4,]    1    1    1    3


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418400.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号