N×N 보드에 다양한 색 사탕이 있고,
인접한 사탕을 한 번 교환할 수 있다.
이때 가장 긴 연속 같은 색 사탕 길이를 구하는 문제.
(i,j)에 대해 (i,j+1) 또는 아래 (i+1,j)와 교환 calculateMaxCandies() 호출 → 최대 연속 길이 계산 calculateMaxCandies()는 다음과 같이 구현:
count++, 다른 컬러면 최대값 갱신 후 count = 1 재설정package BaekJoon.basic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Q3085 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int maxLen = 0;
int N = Integer.parseInt(br.readLine());
char[][] board = new char[N][N];
for (int i = 0; i < N; i++) {
board[i] = br.readLine().toCharArray();
}
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++){
if(j <N-1){
swap(board,i,j,i,j+1);
maxLen=Math.max(maxLen,calculateMaxLength(board,N));
swap(board,i,j,i,j+1);
}
if(i < N-1){
swap(board,i,j, i+1,j);
maxLen = Math.max(maxLen,calculateMaxLength(board,N));
swap(board,i,j,i+1,j);
}
}
}
System.out.println(maxLen);
}
public static void swap(char[][] board, int x1, int y1 , int x2, int y2){
char temp = board[x1][y1];
board[x1][y1] = board[x2][y2];
board[x2][y2] = temp;
}
public static int calculateMaxLength (char[][] board, int N) {
int maxLen = 0;
for(int i=0; i< N ; i++){
int countRow = 1;
int countCol = 1;
for(int j=1; j<N; j++) {
if (board[i][j] == board[i][j - 1]) {
countRow++;
} else {
maxLen = Math.max(maxLen, countRow);
countRow = 1;
}
if (board[j][i] == board[j - 1][i]) {
countCol++;
} else {
maxLen = Math.max(countCol, maxLen);
countCol = 1;
}
}
maxLen= Math.max(maxLen,countRow);
maxLen = Math.max(maxLen,countCol);
}
return maxLen
}
}