【问题标题】:How to find shortest route between two different points on a grid? [closed]如何找到网格上两个不同点之间的最短路径? [关闭]
【发布时间】:2016-10-05 21:22:21
【问题描述】:

我想做一个函数来处理一个文本文件。

这个函数必须处理文本文件,然后找到最短的方法来实现点1到点2。

例子:

* 1 - - - * * 
* * * * - - * 
* * - - - * -  
* * * * - * - 
2 - * * - * - 
* - - * - * -  
* * - - - - -

【问题讨论】:

  • 到目前为止你得到了什么?研究曼哈顿距离算法来实现这一点;这是最简单的。表现出一些努力。

标签: php a-star


【解决方案1】:

它可以被优化,但我有几分钟的时间要杀,所以这就是我想出的。基本思想是逐行读取文件,然后将其分解空间。遍历行,然后是标记每个点所在位置的字符。找出每个 X 和 Y 之间的差异,并根据这些差异生成一个字符串。输出是所采用的路径。

<?php 
//39883901.txt is the text file above
$File = fopen("39883901.txt", "r");
$Lines = array();
$PositionA = array();
$PositionB = array();
if($File) 
{
    while(($line = fgets($File)) !== false)
    {
        $Lines[] = explode(' ', $line);
    }

    fclose($File);
}
if(count($Lines) > 0)
{
    foreach($Lines as $y => $xvalues)
    {
        foreach($xvalues as $x => $value)
        {
            if($value == '1')
            {
                $PositionA['x'] = $x;
                $PositionA['y'] = $y;
            }
            if($value == '2')
            {
                $PositionB['x'] = $x;
                $PositionB['y'] = $y;
            }
        }
    }
    if(isset($PositionA['x'], $PositionA['y'], $PositionB['x'], $PositionB['y']))
    {
        $DifferenceX = $PositionB['x'] - $PositionA['x'];
        $DifferenceY = $PositionB['y'] - $PositionA['y'];
        $PadX = "R";
        $PadY = "D";
        if($DifferenceX < 0)
        {
            $PadX = "L";
            $DifferenceX = $DifferenceX * -1;
        }
        if($DifferenceY < 0)
        {
            $PadY = "U";
            $DifferenceY = $DifferenceY * -1;
        }
        $Travel = "";
        $Travel = str_repeat($PadX, $DifferenceX);
        $Travel .= str_repeat($PadY, $DifferenceY);

        echo "Travel Path: " . $Travel;
        //Travel Path: LDDDD
    }
}
?>

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多