This is very simple to implement.
There are plenty of examples available online in all sorts of languages.
Below is a modified Python snippet that works in the context of Maya mesh geometry.
import maya.OpenMaya as om
import maya.cmds as mc
myMeshObject = "pSphere1"
startVertex = 0
endVertex = 100
edges = {}
p = om.MPlug()
sl = om.MSelectionList()
sl.add(myMeshObject+".worldMesh")
sl.getPlug(0, p)
o = p.asMObject()
pp = om.MFloatPointArray()
om.MFnMesh(o).getPoints(pp, om.MSpace.kWorld)
su = om.MScriptUtil()
su.createFromInt(0)
ptr = su.asIntPtr()
it = om.MItMeshVertex(o)
for i in range(382):
edges[i] = {}
it.setIndex(i, ptr)
a = om.MIntArray()
it.getConnectedVertices(a)
for j in range(a.length()):
edges[i][a[j]] = pp[i].distanceTo(pp[a[j]])
def get_shortest_path(edges, start, end):
nodes_to_visit = {start}
visited_nodes = set()
distance_from_start = {start: 0}
tentative_parents = {}
while nodes_to_visit:
current = min([(distance_from_start[node], node) for node in nodes_to_visit])[1]
if current == end: break
nodes_to_visit.discard(current)
visited_nodes.add(current)
edges2 = edges[current]
unvisited_neighbours = set(edges2).difference(visited_nodes)
for neighbour in unvisited_neighbours:
neighbour_distance = distance_from_start[current] + edges2[neighbour]
if neighbour_distance < distance_from_start.get(neighbour, float('inf')):
distance_from_start[neighbour] = neighbour_distance
tentative_parents[neighbour] = current
nodes_to_visit.add(neighbour)
return _deconstruct_path(tentative_parents, end)
def _deconstruct_path(tentative_parents, end):
if end not in tentative_parents:
return None
cursor = end
path = []
while cursor:
path.append(cursor)
cursor = tentative_parents.get(cursor)
return list(reversed(path))
l = get_shortest_path(edges, startVertex, endVertex)
l.insert(0, startVertex)
l.append(endVertex)
mc.select(cl=True)
for idx in l: mc.select(myMeshObject+".vtx["+str(idx)+"]", add=True)