我想创建一个处理文本文件的函数。
此函数必须处理文本文件,然后找到实现第1点到第2点的最短路径。
示例:
* 1 - - - * *
* * * * - - *
* * - - - * -
* * * * - * -
2 - * * - * -
* - - * - * -
* * - - - - -
答案 0 :(得分:2)
它可以被优化,但我有几分钟可以杀死所以这就是我想出来的。基本思想是逐行读取文件,然后将其展开。迭代线条,然后在每个点的位置标记字符。找出每个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
}
}
?>