douxianji3367 2011-11-16 03:07
浏览 30

MySQL遍历图形数据并获得非循环路径

This one is a hard one for me to solve, basically I have data in a table looking like this:

id  a   b
1   2   4
2   4   2
3   5   2
4   2   5
5   6   2
6   2   6
7   8   6
8   6   8
9   5   6
...

You can see how complex the structure gets if you try to establish what parent has what children:

[2->[4->[2->RECURSIVE], 5->[2->RECURSIVE], 6->[2->RECURSIVE, 8->[6->[8->RECURSIVE]]]], ...]

I fear MySQL alone can't manage to efficiently find a path, but considering I write this in PHP maybe I could write some way for it to maybe first query the 800 lines of code then program an efficient way to parse the data.

The idea is that this function that I am trying to make, let's call it makePath() takes two parameters and returns an array with sub-arrays and the id's referring to a line in the data table.

For example makePath(2,8) would return:

array(array(2,6,8), array(2,5,6,8))

Since these are the only paths going from 2 to 8 without backtracking (i.e. going [2,5,2,6,8] and infinite other combinations of paths.)

I am stuck on how to start all this, hopefully someone brighter than me on the graph and cyclic theory could explain how I should start my code -thanks for your time!

  • 写回答

1条回答 默认 最新

  • douzhang1852 2011-11-17 04:01
    关注

    You should be able to do this with a depth-first search on a directed graph structure. A basic outline would look like:

    1. Create the graph. You'll need at a minimum a list of children and a visiting flag per node.
    2. Call visit with the initial node. For your visit function, you'll need to know the destination node, have a reference to the result array, and keep track of the nodes visited along the current path in a stack.
    3. If the current node is the final node, then add the path traveled (by going through the stack) to the result array.
    4. If the node is being visited, then return.
    5. If the node is not being visited, then
      1. mark the node as being visited
      2. call visit(recursion) with each child
      3. unmark the node as being visited

    If you need help with any of the steps, then please ask.

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站