[Silver I] Z - 1074

JYC·2024년 2월 26일

[BAEKJOON]

목록 보기
50/102

성능 요약

메모리: 14208 KB, 시간: 128 ms

분류

분할 정복, 재귀

제출 일자

2024년 2월 26일 14:48:52

문제 설명

한수는 크기가 2N × 2N인 2차원 배열을 Z모양으로 탐색하려고 한다. 예를 들어, 2×2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다.

N > 1인 경우, 배열을 크기가 2N-1 × 2N-1로 4등분 한 후에 재귀적으로 순서대로 방문한다.

다음 예는 22 × 22 크기의 배열을 방문한 순서이다.

N이 주어졌을 때, r행 c열을 몇 번째로 방문하는지 출력하는 프로그램을 작성하시오.

다음은 N=3일 때의 예이다.

입력

첫째 줄에 정수 N, r, c가 주어진다.

출력

r행 c열을 몇 번째로 방문했는지 출력한다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	static int x=0;
	static int y=0;
	static int count=0;
	public static void main(String[] args) throws IOException{
		BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st =new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken()); //크기
		int r = Integer.parseInt(st.nextToken()); //행
		int c = Integer.parseInt(st.nextToken()); //열
		int result =Z((int)Math.pow(2, n),r,c); //크기는 n*n
		System.out.println(result);

	}
	static int Z(int size,int r,int c) {
		size /=2;//분할 정복
		if(r<x+size && c<y+size) { //왼쪽 위
			count+=(size*size*0);
		}
		else if(r<x+size && c>=y+size) { //오른쪽 위
			count+=(size*size*1);
			y+=size;
		}
		else if(c<y+size) { //왼쪽 아래
			count+=(size*size*2);
			x+=size;
		}
		else { //오른쪽 아래
			count+=(size*size*3);
			x+=size;
			y+=size;
		}
		if(size==1) {//분할 정복 더 못할 경우
			return count;
		}
		return Z(size,r,c);
	}
}

분할 정복 + 재귀를 이용하는 문제이다
[문제 풀이 참고]를 참고했다.

profile
열심히 하기 1일차

0개의 댓글