코테 연습 with Java - 8

아이모·2022년 11월 1일
0

코테

목록 보기
14/15

백준 1987 알파벳

<풀이 중 실수>

문제를 풀던 중 visited 배열을 처음에는 String타입의 arrayList로 선언하여 지나간 문자를 넣어주었는데 시간초과가 발생하였다.
시간 초과를 해결하지 못해서 다른 사람의 풀이를 보았더니 애초에 알파벳 배열을 생성하여 알파벳을 숫자로 사용하였다. 동적 list를 생성하면 시간초과 문제가 일어날 수 있다는 것을 알았다.

<코드>

import java.util.*;
import java.io.*;
public class Main {
	static int R ; 
	static int C;
	static int [][] board;
	static int result;
	static boolean[] visited = new boolean[26];
    static int[] dx = { -1, 1, 0, 0 };
	static int[] dy = { 0, 0, -1, 1 };
	static void draft(int row, int column, int count) {
		if(visited[board[row][column]]) {
			result = Math.max(result, count);
			return;
		}
        visited[board[row][column]] = true;
        for (int i = 0; i < 4; i++) {
            int cx = row + dx[i];
            int cy = column + dy[i];
            if (cx >= 0 && cy >= 0 && cx < R && cy < C) {
                draft(cx, cy, count + 1);
            }

        }
        visited[board[row][column]] = false;
    
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		R = sc.nextInt();
		C = sc.nextInt();
		board = new int [R][C];
		result = 0;
		for(int i = 0; i < R; i++) {
			String word = sc.next();
			for(int j = 0; j < C; j++) {
				board[i][j] = word.charAt(j) - 'A';
			}
		}
		draft(0, 0, 0);
		System.out.println(result);
	}

}
profile
데이터로 보는 실력

0개의 댓글