본문 바로가기

PS/BOJ

[C++] BOJ (백준) 1074 : Z

문제

1074번: Z (acmicpc.net)

 

1074번: Z

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

www.acmicpc.net

코드
#include <iostream>

using namespace std;

int n, r, c;

void input() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n >> r >> c;
}

void solve(int y, int x, int size, int cnt) {
  if (size == 0) {
    cout << cnt;
    return;
  }

  size--;
  int d = 1 << size;
  if (r >= y + d) {
    y += d;
    cnt += d * d * 2;
  }
  if (c >= x + d) {
    x += d;
    cnt += d * d;
  }
  solve(y, x, size, cnt);
}

int main() {
  input();
  solve(0, 0, n, 0);
  return 0;
}
설명

주어진 배열을 4등분하여 그 4개의 위치 중 (r,c)가 속한 위치를 찾는 재귀 함수를 만든다.