[백준] 1987 알파벳

cheeeese·2022년 8월 18일
0

코딩테스트 연습

목록 보기
133/151
post-thumbnail

📖 문제

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

💻 내 코드

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

public class BOJ_1987 {

	static int R, C;
	static char[][] map;
	static int[] dx = { 0, -1, 0, 1 };
	static int[] dy = { -1, 0, 1, 0 };
	static boolean[] visited;
	static int total;
	static int max=Integer.MIN_VALUE;

	public static void main(String[] args) throws IOException {

		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();

		}


		visited = new boolean[26];

		total=0;
		
		visited[map[0][0]-65]=true;
		find(0, 0,1);

		System.out.println(max);
	}


	
	private static void find(int x, int y, int cnt) {
		
		max=Math.max(max, cnt);
		
		for(int i=0;i<4;i++) {
			int nx=x+dx[i];
			int ny=y+dy[i];
			
			if (0 <= nx && nx < R && 0 <= ny && ny < C) {
				
				int c=map[nx][ny];
				if(!visited[c-65]) {					
					visited[c-65]=true;
					find(nx, ny, cnt+1);
					visited[c-65]=false;
				}
				
			}
			
		}
		

	}

}

💡 풀이

  • 문자를 방문했는지 확인하는 배열을 하나 생성
  • 0,0부터 방문 시작
  • 방문한 칸 수를 저장하는 cnt를 매개변수로 함께 받음
  • 방문 가능하면 새로운 칸으로 이동하며 cnt+1
  • 방문하고 난 뒤 방문한 문자를 false로 바꾸어 주어야 탐색이 끝나고 새로운 위치에서 탐색이 가능하다

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN