문제링크 : https://www.acmicpc.net/problem/1987
상하좌우 배열로 하는부분은 구글 검색을 통해 참고했다. 아직은 갈길이 너무 멀다.
import java.io.*;
import java.util.*;
public class Main {
static FastReader scan = new FastReader(); //입력
static StringBuilder sb = new StringBuilder(); //제출답안
static int R, C, count;
static char[][] alphabetBoard;
static ArrayList<Character> visited;
static int[] dx = {1,-1,0,0};//상 하
static int[] dy = {0,0,1,-1};//좌 우
static void input() { //입력
R = scan.nextInt();
C = scan.nextInt();
alphabetBoard = new char[R][C];
for(int row = 0; row < R; row++) {
String inputChar = scan.nextLine();
for(int col = 0; col < C; col++) {
alphabetBoard[row][col] = inputChar.charAt(col);
}
}
}
public static void main(String[] args) {
input(); // 입력
visited = new ArrayList<>();
recFunc(0,0, 0);
System.out.println(count);
}
static void recFunc(int k, int row, int col) {
if(visited.contains(alphabetBoard[row][col])) {
if(k > count) {
count = k;
}
} else {
visited.add(alphabetBoard[row][col]);
for(int i=0; i<4; i++) {
int nx = row + dx[i];
int ny = col + dy[i];
if(nx<0 || ny <0 || nx >R-1 || ny > C-1) continue;
recFunc(k+1,nx, ny);
}
visited.remove(visited.size()-1);
}
}
/*
*
*류호석 강사님 입력 템플릿
*
*/
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
'알고리즘' 카테고리의 다른 글
JAVA 백준1015 수열 정렬(BOJ1015) (0) | 2022.03.13 |
---|---|
JAVA 백준2751 수 정렬하기2(BOJ2751)(cpu 초당 연산속도) (0) | 2022.03.12 |
JAVA 백준2750 수 정렬하기(BOJ2750) (0) | 2022.03.12 |
JAVA 백준10825 국영수(BOJ10825) (0) | 2022.03.12 |
JAVA 백준2529 부등호(BOJ2529) (0) | 2022.03.12 |