지도가 정사각형이므로, 단계별로 가로선 혹은 세로선에 점이 몇개인지 확인을 해보면 규칙을 찾을 수 있다.
📌 규칙
어떤 단계의 한 가로선에 있는 점의 개수는(전 단계의 가로선에 있는 점) + (전 단계의 가로선에 있는 점 - 1)이다.
- 0단계:
- 1단계:
- 2단계:
- 3단계:
- 4단계:
각 단계와 곱해지는 수의 연관관계는 딱히 없으므로, 재귀를 수행하는 메서드의 인자로 단계와 곱해지는 수를 함께 전달하여 독립적으로 계산할 수 있도록 구성하면 된다.
import java.io.*;
import java.util.*;
public class Main {
static int n;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
System.out.println(func(1, 2));
}
public static int func(int step, int num){
int next = num + (num - 1);
if(step == n){
return next * next;
} else {
return func(step + 1, next);
}
}
}