#\
~~~ c++
void Find_Path(int x, int y, int N){/* find word path /
printf("x: %d y: %d N: %d\n", x, y, N);
if(N==leng){
flag = 1;
return; / succes to find word in table and exit */
}
else{
if(table[x+1][y] != -1 && table[x+1][y] == temp[N]){
Find_Path(x+1, y, N+1);
}
else if(table[x+1][y+1] != -1 && table[x+1][y+1] == temp[N]){
Find_Path(x+1, y+1, N+1);
}
else if(table[x][y+1] != -1 && table[x][y+1] == temp[N]){
Find_Path(x, y+1, N+1);
}
else if(table[x-1][y+1] != -1 && table[x-1][y+1] == temp[N]){
Find_Path(x-1, y+1, N+1);
}
else if(table[x-1][y] != -1 && table[x-1][y] == temp[N]){
Find_Path(x-1, y, N+1);
}
else if(table[x-1][y-1] != -1 && table[x-1][y-1] == temp[N]){
Find_Path(x-1, y-1, N+1);
}
else if(table[x][y-1] != -1 && table[x][y-1] == temp[N]){
Find_Path(x, y-1, N+1);
}
else if(table[x+1][y-1] != -1 && table[x+1][y-1] == temp[N]){
Find_Path(x+1, y-1, N+1);
}
}
위의 코드는 BOGGLE문제에서 단어를 찾는 알고리즘입니다. 다른 함수를 통해 첫번째 글자의 위치를 찾고 그 위치를 입력받아서 처음 함수가 실행됩니다. 그리고 9방향중에서 다음 글자가 있는 방향을 찾아서 간뒤 그곳에서 다시 자기자신을 호출하여 다음 글자가 있는 곳을 찾거나 없으면 아무것도 리턴하지 않는 함수인데요.
궁금한 점은 예를들어 저 알고리즘에서 첫번쨰로 택한 경로가 틀린경로라면 제 생각에는 순서대로 쭉 코드가 진행되서 다음으로 택할 경로를 또 확인하고 할줄 알앗는데 가장 첫번쨰로 선택하게 되는 경로로 쭉 가다가 그게 틀린 경로면 함수 전체가 종료 되어 버립니다. 그게 틀린경로면 그 작은 함수만 종료되고 남은 함수들은 마저 다 실행되어야 하는거 아닌가요?
(설명이 먼가 복잡한거 같아 죄송합니다. ㅠ)
oanoelsis
#\
~~~ c++
void Find_Path(int x, int y, int N){/* find word path /
printf("x: %d y: %d N: %d\n", x, y, N);
if(N==leng){
flag = 1;
return; / succes to find word in table and exit */
}
else{
if(table[x+1][y] != -1 && table[x+1][y] == temp[N]){
Find_Path(x+1, y, N+1);
}
else if(table[x+1][y+1] != -1 && table[x+1][y+1] == temp[N]){
Find_Path(x+1, y+1, N+1);
}
else if(table[x][y+1] != -1 && table[x][y+1] == temp[N]){
Find_Path(x, y+1, N+1);
}
else if(table[x-1][y+1] != -1 && table[x-1][y+1] == temp[N]){
Find_Path(x-1, y+1, N+1);
}
else if(table[x-1][y] != -1 && table[x-1][y] == temp[N]){
Find_Path(x-1, y, N+1);
}
else if(table[x-1][y-1] != -1 && table[x-1][y-1] == temp[N]){
Find_Path(x-1, y-1, N+1);
}
else if(table[x][y-1] != -1 && table[x][y-1] == temp[N]){
Find_Path(x, y-1, N+1);
}
else if(table[x+1][y-1] != -1 && table[x+1][y-1] == temp[N]){
Find_Path(x+1, y-1, N+1);
}
}
12년 전