查找节点的路径,树C.

时间:2016-10-30 18:58:21

标签: c tree

您好我正在尝试查找树中给定节点的路径。

我使用树来分析定义为int矩阵的迷宫中的所有可能路径。

这是矩阵:

int room[20][20] =
{
  {0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
};

1表示有一面墙,2表示出口,0表示可用空间

这里是我如何定义节点:

struct node
{
 int i,j; //NODE COORDS
 int key;
 struct node *right;
 struct node *left;
 struct node *up;
 struct node *down;
};

这是我用来在树中插入节点的方法:

void insert(int room[20][20], struct node **leaf, int i, int j)
{

    if( *leaf == 0 )
    {
        *leaf = (struct node*) malloc( sizeof( struct node ) );
        (*leaf)->key = room[i][j];
        (*leaf)->i = i;
        (*leaf)->j = j;
        (*leaf)->left = 0;
        (*leaf)->right = 0;
        (*leaf)->up = 0;
        (*leaf)->down = 0;
    }
    else if((room[i][j+1]==0 || room[i][j+1]==2) && i<20 && j<20 && i>=0 && j+1>=0)//CHECK IF RIGHT IS FREE OR IS EXIT OF THE MAZE
    {
        (*leaf)->key = room[i][j+1];
        insert( room, &(*leaf)->right, i ,j+1 );
    }
    else if((room[i][j-1]==0 || room[i][j-1]==2) && i<20 && j<20 && i>=0 && j-1>=0)//CHECK IF LEFT IS FREE OR IS EXIT OF THE MAZE
    {
        (*leaf)->key = room[i][j-1];
        insert( room, &(*leaf)->left, i ,j-1 );
    }
    else if((room[i+1][j]==0 || room[i+1][j]==2) && i<20 && j<20 && i+1>=0 && j>=0)//CHECK IF DOWN IS FREE OR IS EXIT OF THE MAZE
    {
        (*leaf)->key = room[i+1][j];
        insert( room, &(*leaf)->down, i+1 ,j );
    }
    else if((room[i-1][j]==0 || room[i-1][j]==2) && i<20 && j<20 && i-1>=0 && j>=0)//CHECK IF UP IS FREE OR IS EXIT OF THE MAZE
    {
        (*leaf)->key = room[i-1][j];
        insert( room, &(*leaf)->up, i-1 ,j );
    }
}

初始化树:

struct node *root = 0;
for(i=0;i<400;i++)
insert(room,&root,0,0); //INITIALIZE THE TREE ANALIZING EVERY CELL OF THE MATRIX

一旦我像上面那样初始化树,我想搜索具有值2(退出)的密钥,并且能够找到从该节点到根节点的路径并收集它们之间的每个节点的坐标。

要做到这一点,一旦我找到值为2的节点,我想找到该节点的父节点,依此类推,直到找到根节点,每次我在它们之间找到一个节点,我想存储它&# 39;数组中的coords,所以稍后我可以使用它们绘制出口的路径。

在这种情况下,如何找到值为2的节点?

在这种情况下如何找到给定节点的父节点?

1 个答案:

答案 0 :(得分:0)

这似乎是一个普遍的寻路问题。一种流行的解决方案是实现A* search algorithm。您最终如何构建和遍历数据取决于您,但此算法描述了如何从A点到B(最短距离,避开障碍物)。您应该能够根据自己的情况采用此算法。