알고리즘

<백준> 1074번 자바 알고리즘

changha. 2021. 7. 26. 23:29
import java.util.Scanner;

public class B1074 {
	static int N, r, c, cnt;
	static int[] dx = {0, 1, 0, 1};
	static int[] dy = {0, 0, 1, 1};
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		r = sc.nextInt();
		c = sc.nextInt();
		
		dfs((int) Math.pow(2, N), 0, 0);
	}
	
	static void dfs(int n, int row, int col) {
		if (n == 2) { // 2*2 됐을 때 
			for (int i=0; i< 4; i++) {
				int r2 = row + dy[i];
				int c2 = col + dx[i];
				if (r2 == r && c2 == c) { // 주어진 값과 일치할 때 
					System.out.println(cnt);
					System.exit(0);
				}
				cnt++;
				
			}
			return;
		}
		dfs(n/2, row, col);
		dfs(n/2, row, col + n/2);
		dfs(n/2, row + n/2, col);
		dfs(n/2, row + n/2, col + n/2);
	}

}

많은 블로그를 참고하면서 가장 이해가 잘된 코드를 가져왔다 

 

이제 class 3단계 문제를 푸는데 난이도가 확실히 높아졌다 ㅠ

재귀를 이용하여 푸는 문제다