Sangwon Coding

알파벳 본문

알고리즘/DFS, BFS

알파벳

SW1 2019. 11. 25. 15:22

문제

세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다.

말은 상하좌우로 인접한 네 칸 중의 한 칸으로 이동할 수 있는데, 새로 이동한 칸에 적혀 있는 알파벳은 지금까지 지나온 모든 칸에 적혀 있는 알파벳과는 달라야 한다. 즉, 같은 알파벳이 적힌 칸을 두 번 지날 수 없다.

좌측 상단에서 시작해서, 말이 최대한 몇 칸을 지날 수 있는지를 구하는 프로그램을 작성하시오. 말이 지나는 칸은 좌측 상단의 칸도 포함된다.

입력

첫째 줄에 R과 C가 빈칸을 사이에 두고 주어진다. (1<=R,C<=20) 둘째 줄부터 R개의 줄에 걸쳐서 보드에 적혀 있는 C개의 대문자 알파벳들이 빈칸 없이 주어진다.

출력

첫째 줄에 말이 지날 수 있는 최대의 칸 수를 출력한다.

 

 

import java.util.*;

class Main {
	static int R, C;
	static char[][] board;
	static ArrayList<Character> list = new ArrayList<Character>();	// 지금까지 지나온 알파벳 리스트
	static int[] dx = { 1, 0, -1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static int max = 0;

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		R = scan.nextInt();
		C = scan.nextInt();

		board = new char[R][C];

		for (int i = 0; i < R; i++) {
			String str = scan.next();
			for (int j = 0; j < C; j++) {
				board[i][j] = str.charAt(j);
			}
		}

		list.add(board[0][0]);
		dfs(0, 0, 1);

		System.out.println(max);
	}

	static void dfs(int x, int y, int cnt) {	// dfs
		if (cnt > max) {	// 최대값 구하기
			max = cnt;
		}
		
		for (int i = 0; i < 4; i++) {
			int next_x = x + dx[i];
			int next_y = y + dy[i];

			if (next_x < 0 || next_y < 0 || next_x >= R || next_y >= C || list.contains(board[next_x][next_y]))
				continue;

			list.add(board[next_x][next_y]);
			dfs(next_x, next_y, cnt + 1);
			list.remove(list.size() - 1);
		}
	}
}

 

문제출처

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

'알고리즘 > DFS, BFS' 카테고리의 다른 글

Puyo Puyo  (0) 2019.12.05
빙산  (0) 2019.11.25
연구소  (0) 2019.11.25
경로 찾기  (0) 2019.11.24
케빈 베이컨의 6단계 법칙  (0) 2019.11.22
Comments