矩阵中N步的最长路径

时间:2019-05-18 18:02:32

标签: c algorithm depth-first-search backtracking

在给定起始单元的情况下,我试图在RxC矩阵中找到长度为N的简单路径。该路径应遵循布尔函数给定的限制。目的是稍后使用它来查找矩阵中最长的路径。

我已经设置了解决方案,但是我不知道如何修改它,以了解何时不存在解决方案。

我的解决方案包括使用回溯的DFS方法。解决方案是正确的,但是程序会返回找到的最长路径,而不是说这样的路径不存在。

我知道可用的解决方案也存在类似的问题,但我想了解我的逻辑失败的地方。

这是代码(从一个单元格我们可以在所有8个方向上移动):

Bool DFS(Map *map,Point* srcPt,short steps,Bool (*restrictionCompare)(Point *p1, Point *p2))
{
    Point *target;
    short row = getPointRow(srcPt);
    short col = getPointCol(srcPt);

    // Found N-steps path!
    if (steps == 0)
    {
        puts("Path found!\n");
        return 1;
    }


    //Mark the M[row][col] as visited
    markAsVisited(map,row,col);


    // Iterate over all 8 directions of a cell
    for (short i = 0; i < DIRECTIONS; ++i)
    {
        short coords[2];
        // Get a valid adjacent cell
        if (getNeighbour(map,srcPt,i,coords,restrictionCompare) == FALSE) continue;

        target = getMapPoint(map,coords[0],coords[1]); // This is the valid neighbour


        //if cell wasn't visited before...
        if (isVisited(target) == FALSE)
        {

            // ..recursively call DFS from cell
            if(DFS(map,target,--steps,restrictionCompare) == TRUE)
            {

                // Show point
                showPoint(target);

                return TRUE;
            }                     
        }

    }

    // Backtrack
    markAsUnvisited(map,row,col);
    return FALSE;
}

程序发现的长度路径示例:

path

也欢迎任何有关提高代码效率的建议。

0 个答案:

没有答案
相关问题