๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1937_์š•์‹ฌ์Ÿ์ด ํŒ๋‹ค

๋ฟŒ์•ผ._. 2023. 5. 25. 13:11

Gold III

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1937)

< ์š•์‹ฌ์Ÿ์ด ํŒ๋‹ค >

 

๋ฌธ์ œ ํ’€์ด

 

์ฒ˜์Œ์— dfs๋งŒ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋ ค๊ณ  ํ–ˆ์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ๊ณ  dp๋„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. ์ด๋ฏธ dfs ํƒ์ƒ‰์„ ํ†ตํ•ด ๊ฐ’์„ ๊ตฌํ–ˆ๋‹ค๋ฉด ๋ฐฐ์—ด์— ์ €์žฅํ•ด ๋‘๊ณ  ๋‹ค์‹œ ํƒ์ƒ‰์„ ํ•˜์ง€ ์•Š๋„๋ก ๊ตฌํ˜„ํ•˜์—ฌ ์‹œ๊ฐ„์„ ์ค„์ด๋Š” ๋ฐฉ๋ฒ•์„ ํƒํ•˜์˜€๋‹ค.

 

 

 

 - my solution (Java)

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

public class Main {
	static int arr[][], dp[][], n, result;
	static int dx[] = { -1, 1, 0, 0 };
	static int dy[] = { 0, 0, -1, 1 };

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		n = Integer.parseInt(bf.readLine());
		arr = new int[n][n];
		dp = new int[n][n];
		result = 1;

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(bf.readLine());
			for (int j = 0; j < n; j++) {
				arr[i][j] = Integer.parseInt(st.nextToken());
				dp[i][j] = 1;
			}
		}

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				dfs(i, j);
			}
		}

		System.out.println(result);
	}

	private static int dfs(int i, int j) {
		int max_value = 1;
		for (int k = 0; k < 4; k++) {
			int x = i + dx[k];
			int y = j + dy[k];
			if (x >= 0 && x < n && y >= 0 && y < n && arr[i][j] < arr[x][y]) {

				if (dp[x][y] > 1) {
					if (max_value < 1 + dp[x][y])
						max_value = 1 + dp[x][y];
				}
				else {
					int num = dfs(x, y);
					if (max_value < 1 + num)
						max_value = 1 + num;
				}
			}
		}
		dp[i][j] = max_value;
		if (result < max_value)
			result = max_value;

		return dp[i][j];
	}
}

 

  • Main
    • n : ๋Œ€๋‚˜๋ฌด ์ˆฒ ํฌ๊ธฐ ์ž…๋ ฅ
    • arr: ๋Œ€๋‚˜๋ฌด ์ˆฒ ์ •๋ณด ์ž…๋ ฅ
    • dp: ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ์นธ์˜ ์ •๋ณด ์ €์žฅ
    • arr์— ๋Œ€ํ•ด์„œ ํ•˜๋‚˜์”ฉ ๋‹ค dfs ํƒ์ƒ‰ ํ›„ ์ตœ๋Œ“๊ฐ’ ์ถœ๋ ฅ
  • dfs
    • ํ˜„์žฌ ์œ„์น˜์—์„œ ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰
    • ๋Œ€๋‚˜๋ฌด ์ˆฒ ๋ฒ”์œ„ ์•ˆ์ด๋ฉฐ ์ „ ์ง€์—ญ๋ณด๋‹ค ๋Œ€๋‚˜๋ฌด๊ฐ€ ๋งŽ๋‹ค๋ฉด ์ด๋™
    • ์ด๋™ํ•œ ์œ„์น˜๊ฐ€ ์ด๋ฏธ ํƒ์ƒ‰๋œ ์ง€์—ญ์ด๋ผ dp์— ๊ฐ’์ด ์ €์žฅ๋˜์–ด ์žˆ๋‹ค๋ฉด ๊ทธ ๊ฐ’์„ ํ™œ์šฉํ•˜์—ฌ max๊ฐ’ ๊ตฌํ•˜๊ธฐ/ ํƒ์ƒ‰ํ•œ ๊ณณ์ด ์•„๋‹ˆ๋ผ๋ฉด dfs ํƒ์ƒ‰ ํ›„ max ๊ฐ’ ๊ตฌํ•˜๊ธฐ
    • dp ๊ฐ’ ์—…๋ฐ์ดํŠธ ๋ฐ ์ตœ๋Œ“๊ฐ’ ์ €์žฅ

์ƒ๊ฐ๐Ÿค”