[Codetree] 체크판위에서 2
16 Sep 2026
Reading time ~1 minute
해당 문제는 코드트리 체크판위에서 2에서 풀어보실 수 있습니다.
풀이1(4중 for문) 구현
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int R = sc.nextInt();
int C = sc.nextInt();
char[][] grid = new char[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
grid[i][j] = sc.next().charAt(0);
}
}
int cnt = 0;
for(int i = 1; i < R; i++) {
for(int j = 1; j < C; j++) {
for(int k = i+1; k < R - 1; k++) {
for(int l = j + 1; l < C - 1; l++) {
if(grid[0][0]!=grid[i][j] &&
grid[i][j]!=grid[k][l] &&
grid[k][l]!=grid[R-1][C-1]
) {
cnt++;
}
}
}
}
}
System.out.println(cnt);
}
}
풀이2(DFS) 구현
import java.util.Scanner;
public class Main {
public static int cnt = 0;
static char[][] grid;
static int R,C;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
R = sc.nextInt();
C = sc.nextInt();
grid = new char[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
grid[i][j] = sc.next().charAt(0);
}
}
dfs(0, 0, grid[0][0], 0);
System.out.println(cnt);
}
public static void dfs(int y, int x, char prev, int depth) {
if(depth > 2) return;
if(depth == 2) {
if(y < R-1 && x < C-1 && grid[R-1][C-1] != prev) cnt++;
}
for(int i = y + 1; i < R; i++) {
for(int j = x + 1; j < C; j++) {
if(grid[i][j] != prev) {
dfs(i, j, grid[i][j], depth+1);
}
}
}
}
}