search
HomeBackend DevelopmentPHP Tutorial单源最短路径(dijkstra算法)php实现

做一个医学项目,其中在病例评分时会用到单源最短路径的算法。单源最短路径的dijkstra算法的思路如下:
如果存在一条从i到j的最短路径(Vi.....Vk,Vj),Vk是Vj前面的一顶点。那么(Vi...Vk)也必定是从i到k的最短路径。Dijkstra是以最短路径长度递增,逐次生成最短路径的算法。例如:对于源顶点V0,首先选择其直接相邻的顶点中长度最短的顶点Vi,那么当前已知可得从V0到达Vj顶点的最短距离dist[j]=min{dist[j],dist[i]+cost[i][j]}。假设G=,源点为V0,U={V0}表示已经标记过的顶点集合,dist[i]记录V0到i的最短距离,cost[i][j]表示边i到j的开销。   
1.从V-U中选择使dist[i]值最小的顶点i,将i加入到U中;

2.更新与i直接相邻顶点的dist值。(dist[j]=min{dist[j],dist[i]+cost[i][j]})

3.知道U=V,停止。

利用php特有的性质,其代码如下:

function dijkstra(){			$node_info_arr=array(	//结点的邻接表结构		array(			'node_id'=>0,		//某个结点的id			'next_node'=>array(4,2,1),			'node_type'=>0,			'cost'=>array(10,30,100)			),		array(			'node_id'=>4,		//某个结点的id			'next_node'=>array(3),			'node_type'=>1,			'cost'=>array(50)			),		array(			'node_id'=>3,		//某个结点的id			'next_node'=>array(1),			'node_type'=>1,			'cost'=>array(10)			),		array(			'node_id'=>2,		//某个结点的id			'next_node'=>array(3,1),			'node_type'=>1,			'cost'=>array(60,60)			),		array(			'node_id'=>1,		//某个结点的id			'next_node'=>array(),			'node_type'=>2,			'cost'=>array()			)	);		$start_node_id=false;		//起始结点id	$i_cost=array(array());	//两个节点之间的开销	$i_dist=array();		//起始点到各点的最短距离	$b_mark=array();		//是否加入了	foreach($node_info_arr as &$node_info){		if($node_info['node_type']==0){			$start_node_id=$node_info['node_id'];			//找到初始节点		}		foreach($node_info['next_node'] as $key=>$next_node){			$i_cost[$node_info['node_id']][$next_node]=$node_info['cost'][$key];		}		$i_dist[$node_info['node_id']]='INF';				//初始化为无穷大		$b_mark[$node_info['node_id']]=false;				//初始化未加入	}	if($start_node_id===false){		return '302';	}	//计算初始结点到各节点的最短路径	$i_dist[$start_node_id]=0;	//初始点到其本身的距离为0	$b_mark[$start_node_id]=true;	//初始点加入集合		$current_node_id=$start_node_id;	//最近加入的节点id	$node_count=count($node_info_arr);	for($i=0;$i$val){				if($i_dist[$key]=='INF'||$i_dist[$key]>$i_dist[$current_node_id]+$val){					$i_dist[$key]=$i_dist[$current_node_id]+$val;				}			}		}		foreach($i_dist as $key=>$val){			if(!$b_mark[$key]){				if($val!='INF'&&($min=='INF'||$min>$val)){					$min=$val;					$candidate_node_id=$key;	//候选最近结点id				}			}		}		if($min=='INF'){			break;		}		$current_node_id=$candidate_node_id;		$b_mark[$current_node_id]=true;	}	foreach($i_dist as $key=>$val){		echo $start_node_id.'=>'.$key.':'.$val.'<br>';	}}

 其中例子为图:
    
运行结果为:
    0=>0:0
    0=>4:10
    0=>3:60
    0=>2:30
    0=>1:70


转自: 康瑞的部落  »  单源最短路径php实现


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.