본문 바로가기

카테고리 없음

미로찾기 - 재귀함수(recrusion) 사용, 자바

코드 : 

 

public class Code004{

public static int pathSearch(int[][] Map, int startR,int startC, int GoalR, int GoalC){

System.out.println("("+startR+","+startC+")");
Map[startR][startC] = 1;
if(startR == GoalR && startC == GoalC)
return -1;

if (startR-1 >= 0){
if(Map[startR-1][startC] != 1){
if(pathSearch(Map, startR-1, startC,GoalR,GoalC) ==-1)
return -1;
}
}

if (startR+1 < 7 ){
if(Map[startR+1][startC] != 1){
if(pathSearch(Map, startR+1, startC,GoalR,GoalC) ==-1)
return -1;
}
}

if (startC-1 >= 0 ){
if(Map[startR][startC-1] != 1){
if(pathSearch(Map, startR, startC-1,GoalR,GoalC) ==-1)
return -1;
}
}

if (startC+1 < 7 ){
if(Map[startR][startC+1] != 1){
if(pathSearch(Map, startR, startC+1,GoalR,GoalC) ==-1)
return -1;
}
}
return 0;
}

public static void main(String[] args){
int[][] Map = {
{0,1,0,0,0,1,0},
{0,1,0,1,0,1,0},
{0,1,0,1,0,1,0},
{0,0,0,1,0,1,0},
{0,1,0,1,0,1,0},
{0,1,0,1,0,1,0},
{0,1,0,1,0,0,0}
};
pathSearch(Map, 0,0,0,6);
}
}