미로찾기 알고리즘 기초부분.
인터넷강의를 들으면서 코드화 시킴.
Recursion으로써 재귀함수 연습을 위함.
인터넷강의를 들으면서 코드화 시킴.
Recursion으로써 재귀함수 연습을 위함.
package recursive;
public class Maze {
//6 6사이즈 미로
static int[][] maze = {
{0,0,0,0,0,0},
{0,1,1,1,0,1},
{0,1,0,1,0,0},
{0,0,0,0,1,0},
{0,1,1,0,1,1},
{0,0,1,0,0,0},
};
private static final int PATHWAY_COLOR = 0; //길
private static final int WALL_COLOR = 1; //벽
private static final int BLOCK_COLOR = 2; //길없음
private static final int PATH_COLOR = 3; //통로
public static void main(String[] args){
printMaze();
findPath(0,0);
System.out.println("-----------");
printMaze();
}
static boolean findPath(int x, int y){
//1.주어진 배열 외의 값일경우 무조건 false
if(x<0 || y<0 || x>=6 || y>=6) return false;
//2.길이 아니라면 false
else if(maze[x][y]!=PATHWAY_COLOR) return false;
//3.출구면 true
else if(x==5 && y==5){
maze[x][y] = PATH_COLOR;
return true;
}
//4.4방향으로 통로검색
else {
//방문 기록
maze[x][y] = PATH_COLOR;
if(findPath(x-1,y) || findPath(x,y+1) || findPath(x+1,y) || findPath(x,y-1)){
return true;
}
//길없음
maze[x][y] = BLOCK_COLOR;
return false;
}
}
//미로출
static void printMaze(){
for(int i=0; i<6; i++){
for(int j=0; j<6; j++){
System.out.print(maze[i][j] + " ");
}
System.out.println("");
}
}
}
댓글
댓글 쓰기