🔗 백준 3085 - 사탕게임
문제


알고리즘 분류
풀이
1. 배열 입력
n = Integer.parseInt(br.readLine());
candy = new char[n][n];
for(int i = 0; i<n; i++){
String str = br.readLine();
for(int j = 0; j<candy[i].length; j++){
candy[i][j] = str.charAt(j);
}
}
2. 가로(오른쪽)으로 사탕 교환하며 최대갯수 확인
for(int i = 0; i<n; i++){
for(int j = 0; j<n-1; j++){
char temp = candy[i][j];
candy[i][j] = candy[i][j+1];
candy[i][j+1] = temp;
count();
temp = candy[i][j];
candy[i][j] = candy[i][j+1];
candy[i][j+1] = temp;
}
}
3. 세로(아래)로 사탕 교환하며 최대갯수 확인
for(int i = 0; i<n; i++){
for(int j = 0; j<n-1; j++){
char temp = candy[j][i];
candy[j][i] = candy[j+1][i];
candy[j+1][i] = temp;
count();
temp = candy[j][i];
candy[j][i] = candy[j+1][i];
candy[j+1][i] = temp;
}
}
4. 최대 개수를 확인하는 함수
private static void count() {
for(int i = 0; i<n; i++){
int count = 1;
for(int j = 0; j<n-1; j++){
if (candy[i][j] == candy[i][j+1])
count++;
else count=1;
max = Math.max(max, count);
}
}
for(int i = 0; i<n; i++){
int count = 1;
for(int j = 0; j<n-1; j++){
if (candy[j][i] == candy[j+1][i])
count++;
else count = 1;
max = Math.max(max, count);
}
}
}
전체 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static char[][] candy;
static int n;
static int max = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
candy = new char[n][n];
for(int i = 0; i<n; i++){
String str = br.readLine();
for(int j = 0; j<candy[i].length; j++){
candy[i][j] = str.charAt(j);
}
}
for(int i = 0; i<n; i++){
for(int j = 0; j<n-1; j++){
char temp = candy[i][j];
candy[i][j] = candy[i][j+1];
candy[i][j+1] = temp;
count();
temp = candy[i][j];
candy[i][j] = candy[i][j+1];
candy[i][j+1] = temp;
}
}
for(int i = 0; i<n; i++){
for(int j = 0; j<n-1; j++){
char temp = candy[j][i];
candy[j][i] = candy[j+1][i];
candy[j+1][i] = temp;
count();
temp = candy[j][i];
candy[j][i] = candy[j+1][i];
candy[j+1][i] = temp;
}
}
System.out.println(max);
}
private static void count() {
for(int i = 0; i<n; i++){
int count = 1;
for(int j = 0; j<n-1; j++){
if (candy[i][j] == candy[i][j+1])
count++;
else count=1;
max = Math.max(max, count);
}
}
for(int i = 0; i<n; i++){
int count = 1;
for(int j = 0; j<n-1; j++){
if (candy[j][i] == candy[j+1][i])
count++;
else count = 1;
max = Math.max(max, count);
}
}
}
}