개미 등반 극 경로 알고리즘의 PHP 버전

WBOY
풀어 주다: 2016-08-08 09:20:24
원래의
1174명이 탐색했습니다.
<?php
/**
 * 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。
 * 木杆很细,不能同时通过一只蚂蚁。开始 时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,
 * 但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。
 * 编写程序,求所有蚂蚁都离开木杆 的最小时间和最大时间。
 */
function add2($directionArr, $count, $i) {
	if(0 > $i) { // 超出计算范围
		return $directionArr;
	}
	if(0 == $directionArr[$i]) { // 当前位加1
		$directionArr[$i] = 1;
		return $directionArr;
	}
	$directionArr[$i] = 0;
	return add2($directionArr, $count, $i - 1); // 进位
}

$positionArr = array( // 所在位置
	3,
	7,
	11,
	17,
	23
);

function path($positionArr) { // 生成测试路径
	$pathCalculate = array();
	$count = count($positionArr);
	$directionArr = array_fill(0, $count, 0); // 朝向
	$end = str_repeat('1', $count);
	while (true) {
		$path = implode('', $directionArr);
		$pathArray = array_combine($positionArr, $directionArr);
		$total = calculate($positionArr, $directionArr);
		$pathCalculate['P'.$path] = $total;
		if($end == $path) { // 遍历完成
			break;
		}
		$directionArr = add2($directionArr, $count, $count - 1);
	}
	return $pathCalculate;
}

function calculate($positionArr, $directionArr) {
	$total = 0; // 总用时
	$length = 27; // 木杆长度
	while ($positionArr) {
		$total++; // 步增耗时
		$nextArr = array(); // 下一步位置
		foreach ($positionArr as $key => $value) {
			if(0 == $directionArr[$key]) {
				$next = $value - 1; // 向0方向走一步
			} else {
				$next = $value + 1; // 向1方向走一步
			}
			if(0 == $next) { // 在0方向走出
				continue;
			}
			if($length == $next) { // 在1方向走出
				continue;
			}
			$nextArr[$key] = $next;
		}
		$positionArr = $nextArr;
		foreach ($nextArr as $key => $value) {
			$findArr = array_keys($positionArr, $value);
			if(count($findArr) < 2) { // 没有重合的位置
				continue ;
			} 
			foreach ($findArr as $findIndex) {
				$directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1; // 反向处理
				unset($positionArr[$findIndex]);
			}
		}
	}
	return $total;
}

$pathCalculate = path($positionArr);
echo &#39;<pre class="brush:php;toolbar:false">calculate-';
print_r($pathCalculate);
echo 'sort-';
asort($pathCalculate);
print_r($pathCalculate);
로그인 후 복사

저작권 안내: 이 글은 해당 블로거의 원본 글이므로 블로거의 허락 없이 복제할 수 없습니다.

위 내용은 PHP 버전의 개미기둥 등반 경로 알고리즘을 관련 내용을 포함하여 소개한 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!