This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to find the shortest path between the given two roads. (For example, find shortest path between road NH220 to NH320)
Input Data:
1 2 3 4 5 6 7 8 9 10 |
ID FromRoadNo ToRoadNo Distance ----------- ---------- -------- ----------- 1 NH108 NH100 50 2 NH100 NH120 70 3 NH108 NH120 100 4 NH110 NH220 90 5 NH108 NH110 60 6 NH220 NH150 70 7 NH150 NH320 30 8 NH220 NH320 150 |
Expected Output: For shortest path between road NH220 to NH320
1 2 3 |
RequireRoads TotalDistance ------------------------ ------------- .NH220.NH150..NH320. 100 |
Create a table with data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CREATE TABLE Roads ( ID INT ,FromRoadNo CHAR(5) ,ToRoadNo CHAR(5) ,Distance INT ) GO INSERT INTO Roads VALUES (1,'NH108','NH100',50) ,(2,'NH100','NH120',70) ,(3,'NH108','NH120',100) ,(4,'NH110','NH220',90) ,(5,'NH108','NH110',60) ,(6,'NH220','NH150',70) ,(7,'NH150','NH320',30) ,(8,'NH220','NH320',150) GO |
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
DECLARE @StartingRoadNo AS VARCHAR(50) = 'NH220' DECLARE @EndingRoadNo AS VARCHAR(50) = 'NH320' ;WITH CTE AS ( SELECT ToRoadNo , CASE WHEN FromRoadNo IS NULL THEN CAST('.'+ISNULL(FromRoadNo,ToRoadNo)+'.' AS VARCHAR(MAX)) WHEN FromRoadNo IS NOT NULL THEN CAST('.'+FromRoadNo+'.'+ToRoadNo+'.' AS VARCHAR(MAX)) END RequireRoads , Distance TotalDistance FROM Roads WHERE ( FromRoadNo = @StartingRoadNo ) UNION ALL SELECT a.ToRoadNo , c.RequireRoads+'.'+a.ToRoadNo+'.' RequireRoads ,TotalDistance + a.Distance TotalDistance FROM Roads a INNER JOIN CTE c ON a.FromRoadNo = c.ToRoadNo ) ,CTE2 AS ( SELECT * , RANK() OVER (ORDER BY TotalDistance) rnk FROM CTE WHERE ToRoadNo = @EndingRoadNo AND PATINDEX('%'+@EndingRoadNo+'%',RequireRoads) > 0 ) SELECT RequireRoads, TotalDistance FROM CTE2 WHERE rnk = 1 |
Please try the different solution for this puzzle and share it via comment...