You will have to use bmesh.
A bmesh object provides a much more advanced way of interrogating a mesh than as merely a set of vert/edge/face sequences. Given only raw vert/edge/face data, consisting of indices and lists of indices, you could of course build your own model of the inter-relations between elements of the mesh, making several passes over the mesh, noting various states such as selection, deducing which vertex is 'neighbor' to which others, and so forth. Thank Joe, you don't have to do all that.
All you have to do is
bm = bmesh.from_edit_mesh(mesh), and that
bm will have topological-relationship information already figured out. For examples of what I mean by topological-relationship information: You are able to ask a vertex for it's
link_edges, and subsequently ask one of those edges for it's
other_vert(vert) given the one you already have, to find the other, and then if it's selected, that is your next group.
There is even a selection history for you: BMesh.select_history, such that
bm.select_history.active will be your group zero vertex. (If you are in vertex mode.)
While I can't write your script for you – only you know the particulars – I'd hate to leave you hanging without some code example, so here's a template I had from a while ago, from when I was testing some things in bmesh. It's just a bunch of boilerplate, but it puts you at a convenient place to test bmesh things:
bl_idname = "bmopex.bmop"
bl_label = "Bmopex:Bmop"
ob = context.active_object
mesh = ob.data
bm = bmesh.from_edit_mesh(mesh)
return context.active_object and \
context.active_object.type == 'MESH' and \
context.active_object.mode == 'EDIT' and \
# vertex mode ^