[백준] 1987. 알파벳(골드4)

백준(골드4) - 1987. 알파벳(골드4)



풀이

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

public class Main {
	public static char[][] map;
	public static int r,c;
	public static boolean[] visited =  new boolean[26];
	static int[] dx = { -1, 0, 1, 0 };
	static int[] dy = { 0, -1, 0, 1 };
	static int cnt = 1;
	static int ans = 1;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		r = Integer.parseInt(st.nextToken());
		c = Integer.parseInt(st.nextToken());
		map = new char[r][c];
		
		for (int i = 0; i < r; i++) {
			map[i] = br.readLine().toCharArray();
			for (int j = 0; j < c; j++) {
				map[i][j] = (char) (map[i][j]-'A');
			}
		}
		
		dfs(map, visited, 0, 0);
	    System.out.println(ans);
		
	}
	
	public static void dfs(char[][] map, boolean[] visited, int y, int x) {
	    int idx = map[y][x];
	 
	    visited[idx] = true;
	 
	    for (int i = 0; i < 4; i++) {
	        int ny = y + dy[i];
	        int nx = x + dx[i];
	 
	        if (-1 < nx && nx < c && -1 < ny && ny < r) {
	            int next = map[ny][nx];
	 
	            if (!visited[next]) {
	                ans = Math.max(++cnt, ans);
	                dfs(map, visited, ny, nx);
	            }
	 
	        }
	    }
	
	    --cnt;
	    visited[idx] = false;
	}

}

좋은 웹페이지 즐겨찾기