๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
2๏ธโƒฃ Java/Problem Solving

[Java Algorithm] ์•ŒํŒŒ๋ฒณ BOJ #1987

by seolhee2750 2022. 8. 16.
๋ฌธ์ œ

https://www.acmicpc.net/problem/1987

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	
	static int r, c;
	static char[][] board;
	static int max = 0;
	
	public static void dfs(int x, int y, boolean[] alphabet, int cnt) {
		if(x < 0 || y < 0 || x >= r || y >= c) return;
		if(alphabet[(int)board[x][y]-65]) { // ์ด๋ฏธ ์“ฐ์—ฌ์ง„ ์•ŒํŒŒ๋ฒณ ๋งŒ๋‚  ์‹œ ๋ฆฌํ„ด
			max = Math.max(max, cnt);
			return;
		}
		
		alphabet[(int)board[x][y]-65] = true; // ํ˜„์žฌ ์•ŒํŒŒ๋ฒณ์ด ์“ฐ์˜€์Œ์„ ํ‘œ์‹œ
		dfs(x-1, y, alphabet, cnt+1);
		dfs(x, y-1, alphabet, cnt+1);
		dfs(x+1, y, alphabet, cnt+1);
		dfs(x, y+1, alphabet, cnt+1);
		alphabet[(int)board[x][y]-65] = false;
	}

	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		st = new StringTokenizer(in.readLine());
		r = Integer.parseInt(st.nextToken());
		c = Integer.parseInt(st.nextToken());
		
		board = new char[r][c];
		for(int i = 0; i < r; i++) {
			String now = in.readLine();
			for(int j = 0; j < c; j++) {
				board[i][j] = now.charAt(j);
			}
		}
		
		dfs(0, 0, new boolean[26], 0);
		System.out.println(max);
	}

}

๐Ÿ‘‰ DFS ๋ฌธ์ œ

  • ํƒ์ƒ‰๋งˆ๋‹ค ์–ด๋–ค ์•ŒํŒŒ๋ฒณ์ด ์“ฐ์˜€๋Š”์ง€ ์ฒดํฌํ•ด์ค„ alphabet ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค.
    ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๋Œ€๋กœ ์ฒดํฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ–ˆ๋Š”๋ฐ,
    ์ฒดํฌํ•  ๋•Œ๋Š” ํ•ด๋‹นํ•˜๋Š” ์•ŒํŒŒ๋ฒณ์„ intํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•œ ํ›„, 65๋ฅผ ๋นผ์ฃผ์–ด ์ธ๋ฑ์Šค๋กœ ์‚ฌ์šฉํ–ˆ๋‹ค.
  • dfs ํƒ์ƒ‰๋งˆ๋‹ค ์“ฐ์ธ ์•ŒํŒŒ๋ฒณ์„ ์ฒดํฌํ•˜๊ณ , ๋ช‡ ๋ฒˆ์งธ ์•ŒํŒŒ๋ฒณ์ธ์ง€ ์นด์šดํŒ…ํ•ด์ฃผ์—ˆ๋Š”๋ฐ,
    ์ด๋ฏธ ์“ฐ์—ฌ์ง„ ์•ŒํŒŒ๋ฒณ์„ ๋˜๋‹ค์‹œ ๋งŒ๋‚˜๋ฉด ๊ทธ ๋•Œ๋Š” max ๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๊ณ  ๋ฆฌํ„ดํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค. ํ•˜์ง€๋งŒ! ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ๋„˜ ์•ˆ์ข‹์•„์„œ ๋‹ค์‹œ ํ•œ ๋ฒˆ ๋ด์•ผ ํ•  ๋“ฏ ์‹ถ๋‹ค.

๋Œ“๊ธ€