본문 바로가기
알고리즘

recursion으로 미로찾기

by 멋진 개구리 2020. 6. 23.
반응형

미로찾기

package recursion;

public class Maze {

	private static int N = 8;
	private static int[][] maze = { 
			{ 0, 0, 0, 0, 0, 0, 0, 1 }, 
			{ 0, 1, 1, 0, 1, 1, 0, 1 }, 
			{ 0, 0, 0, 1, 0, 0, 0, 1 },
			{ 0, 1, 0, 0, 1, 1, 0, 0 }, 
			{ 0, 1, 1, 1, 0, 0, 1, 1 }, 
			{ 0, 1, 0, 0, 0, 1, 0, 1 },
			{ 0, 0, 0, 1, 0, 0, 0, 1 }, 
			{ 0, 1, 1, 1, 0, 1, 0, 0 }
			};

	private static final int PATHWAY_COLOR = 0;
	private static final int WALL_COLOR = 1;
	private static final int BLOCKED_COLOR = 2;
	private static final int PATH_COLOR = 3;

	public static boolean findMazePath(int x, int y) {

		if (x < 0 || y < 0 || x >= N || y >= N)
			return false; // 유효범위지정 범위밖이면 false를 리턴..
		else if (maze[x][y] != PATHWAY_COLOR)
			return false; //1,2,3 이면 false 2는 방문했던곳 
		else if (x == N - 1 && y == N - 1) {
			maze[x][y] = PATH_COLOR; //최종 지점  
			return true;
		} else {  //일반적인 경우
			maze[x][y] = PATH_COLOR; //미로 출구는 3 
			if (findMazePath(x - 1, y) || findMazePath(x, y + 1) || findMazePath(x + 1, y) || findMazePath(x, y - 1)) {
				return true;
			}
			maze[x][y] = BLOCKED_COLOR; //이미 가본곳 - 출구없는곳
			return false;
		}
	}
	public static void main(String[] args) {
		findMazePath(0, 0);
		for (int i = 0; i < maze.length; i++) {
			for (int j = 0; j < maze.length; j++) {
				System.out.print(maze[i][j]);
				
			}
			System.out.println(" ");
		}
	}
}

반응형

'알고리즘' 카테고리의 다른 글

최댓값 구하는 알고리즘_java  (0) 2020.06.16
recursion - 순차탐색, 이진트리탐색  (0) 2020.06.09
순환함수(재귀함수, Recursion)  (0) 2020.06.04

댓글