[백준] 17265 나의 인생에는 수학과 함께

` dfs


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class B17265 {
	static int N,max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
	static char arr[][];
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
        N = Integer.parseInt(br.readLine());
        arr = new char[N][N];
        
        for (int i = 0; i <N; i++) {
        	st = new StringTokenizer(br.readLine());
			for (int j = 0; j <N; j++) {
				arr[i][j] = st.nextToken().charAt(0);
			}
		}
        
        dfs(0, 0, arr[0][0]-'0', arr[0][0]);
		System.out.println(max + " " + min);
	}
	
	public static void dfs(int x, int y, int result, char oper) {
		int get = arr[x][y] - '0';
		// 숫자일 경우 연산
		if(get >= 0 && get <= 5) {
			if(oper == '+')
				result += get;
			else if(oper == '-')
				result -= get;
			else if(oper == '*')
				result *= get;
		}
		// 연산자일 경우 
		else { 
			oper = arr[x][y];
		}
		
		if(x == N-1 && y == N-1) {
			max = Math.max(result, max);
			min = Math.min(result, min);
			return;
		}

		if(x < N-1) {
			dfs(x+1, y, result, oper);
		}

		if(y < N-1) {
			dfs(x, y+1, result, oper);
		}
	}
}
updatedupdated2021-04-122021-04-12
Load Comments?