이전에 질문을 받았지만 모든 게시물에서 답변을 찾지 못했습니다. 누군가 제발 나를 그래프에있는 모든 해밀턴 경로를 열거하는 알고리즘을 제안 해 주시겠습니까?* all * hamiltonian 경로를 열거하십시오.
약간의 배경 : 각 해밀턴 경로를 나열하고 몇 가지 분석을하고 결과를 반환해야하는 문제에 대해 연구하고 있습니다. 이를 위해 가능한 모든 해밀턴 경로를 열거 할 수 있어야합니다.
감사합니다.
이전에 질문을 받았지만 모든 게시물에서 답변을 찾지 못했습니다. 누군가 제발 나를 그래프에있는 모든 해밀턴 경로를 열거하는 알고리즘을 제안 해 주시겠습니까?* all * hamiltonian 경로를 열거하십시오.
약간의 배경 : 각 해밀턴 경로를 나열하고 몇 가지 분석을하고 결과를 반환해야하는 문제에 대해 연구하고 있습니다. 이를 위해 가능한 모든 해밀턴 경로를 열거 할 수 있어야합니다.
감사합니다.
제안 된대로 BFS/DFS를 사용하지만 첫 번째 해결 방법에서는 중단하지 마십시오. BFS/DFS 기본 사용 (이 경우)은 모든 솔루션을 찾을 수 있습니다. 첫 번째 옵션에서 중지하려면 조건을 입력해야합니다.
감사합니다. "해결책"이 무엇을 의미하는지 자세히 설명해 주시겠습니까? 내가 아는 한 그래프에서 DFS를 실행하면 방문한 노드 시퀀스 (예 : 정점 A, B, C, D가있는 그래프의 경우 A -> B -> C -> D)가 제공됩니다. 그러나 모든 가능한 경로를 '탐색'하지 않습니다. 정교하게 주시겠습니까? –
DFS와 BFS 모두 특정 노드에서 시작하는 가능한 모든 경로를 제공합니다. 이 해밀턴 경로에서 길이가 그래프의 크기와 정확히 같고 각 노드가 정확히 한 번 존재합니다. 그래서 5 개의 노드를 가진 그래프가 있고 p1-> p2-> p3-> p4-> p5의 경로가 있다면 이는 해밀턴 경로입니다. 또한 각 노드에서 검색을 시작해야합니다. – SinistraD
감사합니다. SinistraD, 매우 도움이됩니다! –
내 자바 코드 (절대 재귀 법에 의한)
알고리즘 :
+가 볼 수있는 다른 지점에 연결 한 시점에서 시작 (경로를 형성한다).
+ 그래프의 모든 점을 연결할 때까지 경로를 제거하고 재귀 적으로 새로운 점에서 새 경로를 찾습니다. 캔트 최신 포인트
public class HamiltonPath {
public static void main(String[] args){
HamiltonPath obj = new HamiltonPath();
int[][]x = {{0,1,0,1,0}, //Represent the graphs in the adjacent matrix forms
{1,0,0,0,1},
{0,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}};
int[][]y = {{0,1,0,0,0,1},
{1,0,1,0,0,1},
{0,1,0,1,1,0},
{0,0,1,0,0,0},
{0,0,1,0,0,1},
{1,1,0,0,1,0}};
int[][]z = {{0,1,1,0,0,1},
{1,0,1,0,0,0},
{1,1,0,1,0,1},
{0,0,1,0,1,0},
{0,0,0,1,0,1},
{1,0,1,0,1,0}};
obj.allHamiltonPath(y); //list all Hamiltonian paths of graph
//obj.HamiltonPath(z,1); //list all Hamiltonian paths start at point 1
}
static int len;
static int[]path;
static int count = 0;
public void allHamiltonPath(int[][]x){ //List all possible Hamilton path in the graph
len = x.length;
path = new int[len];
int i;
for(i = 0;i<len;i++){ //Go through column(of matrix)
path[0]=i+1;
findHamiltonpath(x,0,i,0);
}
}
public void HamiltonPath(int[][]x, int start){ //List all possible Hamilton path with fixed starting point
len = x.length;
path = new int[len];
int i;
for(i = start-1;i<start;i++){ //Go through row(with given column)
path[0]=i+1;
findHamiltonpath(x,0,i,0);
}
}
private void findHamiltonpath(int[][]M,int x,int y,int l){
int i;
for(i=x;i<len;i++){ //Go through row
if(M[i][y]!=0){ //2 point connect
if(detect(path,i+1))// if detect a point that already in the path => duplicate
continue;
l++; //Increase path length due to 1 new point is connected
path[l]=i+1; //correspond to the array that start at 0, graph that start at point 1
if(l==len-1){//Except initial point already count =>success connect all point
count++;
if (count ==1)
System.out.println("Hamilton path of graph: ");
display(path);
l--;
continue;
}
M[i][y]=M[y][i]=0; //remove the path that has been get and
findHamiltonpath(M,0,i,l); //recursively start to find new path at new end point
l--; // reduce path length due to the failure to find new path
M[i][y] = M[y][i]=1; //and tranform back to the inital form of adjacent matrix(graph)
}
}path[l+1]=0; //disconnect two point correspond the failure to find the..
} //possible hamilton path at new point(ignore newest point try another one)
public void display(int[]x){
System.out.print(count+" : ");
for(int i:x){
System.out.print(i+" ");
}
System.out.println();
}
private boolean detect(int[]x,int target){ //Detect duplicate point in Halmilton path
boolean t=false;
for(int i:x){
if(i==target){
t = true;
break;
}
}
return t;
}
} 깊이 우선 철저한 검색이 당신에게 답을 제공
에서 해밀턴 경로를 형성하는 경우
+ 경로를 제거하고 초기 그래프에 철수.
http://puzzledraccoon.wordpress.com/2012/06/07/how-to-cool-a-data-center/
솔루션 Python3에서 :
def hamiltonians(G, vis = []):
if not vis:
for n in G:
for p in hamiltonians(G, [n]):
yield p
else:
dests = set(G[vis[-1]]) - set(vis)
if not dests and len(vis) == len(G):
yield vis
for n in dests:
for p in hamiltonians(G, vis + [n]):
yield p
G = {'a' : 'bc', 'b' : 'ad', 'c' : 'b', 'd' : 'ac'}
print(list(hamiltonians(G)))
하면 일반 검색을 시도해 봤어 난 그냥 (코드 포함)이 문제에 대한 자바 구현에 쓰기 업을 완료? BFS/DFS? 그래프가 얼마나 큽니까? – slezica
산티아고, 답장을 보내 주셔서 감사합니다. 내 그래프는 작습니다 (6-7 노드). 나는 BFS와 DFS에 대해 생각해 봤지만 모든 가능한 경로를 나열하는 것이 아니라 특정 키를 검색하는 데 BFS/DFS가 사용된다고 가정합니다. BFS/DFS가 * 모든 * 가능한 사이클을 생성하도록하려면 어떻게합니까? –
정규 BFS/DFS는 일치하는 첫 번째 키를 찾은 후 중지하도록 조건이 지정됩니다. 당신은 단지 그것을 변경해야만합니다. 가능한 경우 전체 그래프를 걸고 그것을 솔루션으로 기록하십시오. – slezica