//
//
求图任意两点的最短距离
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<list>
#include
<algorithm>
enum
{
Vertex_No_Connection
= -1,
Vertex_Total_Number
= 5,
Vertex_Max_Edge_Value
= 10000,
};
/*
int arrayPathScheme[Vertex_Total_Number][Vertex_Total_Number ] =
{
0, 10, -1, 30, 100,
-1, 0, 50, -1, -1,
-1, -1, 0, -1, 10,
-1, -1, 20, 0, 60,
-1, -1, -1, -1, 0,
};
*/
int
arrayPathScheme
[
Vertex_Total_Number
][
Vertex_Total_Number
] =
{
0, 10, 2, 30, 100,
50, 0, 50, 1, 6,
3, 1, 0, 4, 10,
1, 4, 20, 0, 60,
6, 2, 3, 6, 0,
};
int
arrayShortestPath
[
Vertex_Total_Number
][
Vertex_Total_Number
];
//
记录任意两点最短距离的数组
int
arrayPreNode
[
Vertex_Total_Number
][
Vertex_Total_Number
];
//
记录任意两点最短距离的
前驱结点
void
Print
(
int
nPre
,
int
nNext
);
int
_tmain
(
int
argc
,
_TCHAR
*
argv
[])
{
// Init Shortest Path
for
(
int
i
= 0;
i
<
Vertex_Total_Number
; ++
i
)
{
for
(
int
j
= 0;
j
<
Vertex_Total_Number
; ++
j
)
{
if
(
Vertex_No_Connection
==
arrayPathScheme
[
i
][
j
] )
arrayShortestPath
[
i
][
j
] =
Vertex_Max_Edge_Value
;
else
arrayShortestPath
[
i
][
j
] =
arrayPathScheme
[
i
][
j
];
arrayPreNode
[
i
][
j
] =
i
;
}
}
for
(
int
k
= 0;
k
<
Vertex_Total_Number
; ++
k
)
{
for
(
int
i
= 0;
i
<
Vertex_Total_Number
; ++
i
)
{
for
(
int
j
= 0;
j
<
Vertex_Total_Number
; ++
j
)
{
if
(
arrayShortestPath
[
i
][
k
] +
arrayShortestPath
[
k
][
j
] <
arrayShortestPath
[
i
][
j
] )
{
arrayShortestPath
[
i
][
j
] =
arrayShortestPath
[
i
][
k
] +
arrayShortestPath
[
k
][
j
];
arrayPreNode
[
i
][
j
] =
k
;
}
}
}
}
// Print
for
(
int
i
= 0;
i
<
Vertex_Total_Number
; ++
i
)
{
for
(
int
j
= 0;
j
<
Vertex_Total_Number
; ++
j
)
{
if
(
arrayShortestPath
[
i
][
j
] ==
Vertex_Max_Edge_Value
)
std
::
cout
<<
i
<<
" To "
<<
j
<<
" No Path"
<<
std
::
endl
;
else
if
(
arrayShortestPath
[
i
][
j
] == 0 )
std
::
cout
<<
i
<<
" To "
<<
j
<<
" Path Distance is 0 "
<<
std
::
endl
;
else
{
std
::
cout
<<
i
<<
" To "
<<
j
<<
" Distance "
<<
arrayShortestPath
[
i
][
j
]<<
std
::
endl
;
std
::
cout
<<
" Path ....."
;
Print
(
i
,
j
);
std
::
cout
<<
j
<<
std
::
endl
;
}
}
}
system
(
"pause"
);
return
0;
}
void
Print
(
int
nPre
,
int
nNext
)
{
int
nNewNext
=
arrayPreNode
[
nPre
][
nNext
];
if
(
nNewNext
==
nPre
)
{
std
::
cout
<<
nNewNext
<<
"-->"
;
return
;
}
Print
(
nPre
,
nNewNext
);
std
::
cout
<<
nNewNext
<<
"-->"
;
}
当数组为
int
arrayPathScheme
[
Vertex_Total_Number
][
Vertex_Total_Number
] =
{
0, 10, 2, 30, 100,
50, 0, 50, 1, 6,
3, 1, 0, 4, 10,
1, 4, 20, 0, 60,
6, 2, 3, 6, 0,
};
其 结果为
int
arrayPathScheme
[
Vertex_Total_Number
][
Vertex_Total_Number
] =
{
0, 10, -1, 30, 100,
-1, 0, 50, -1, -1,
-1, -1, 0, -1, 10,
-1, -1, 20, 0, 60,
-1, -1, -1, -1, 0,
};