[Codetree] 숨은 단어 찾기 2
30 Sep 2026
Reading time ~2 minutes
해당 문제는 코드트리 숨은 단어 찾기 2에서 풀어보실 수 있습니다.
풀이1 구현
import java.util.Scanner;
public class Main {
static final int DIR_NUM = 8;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.next();
}
// Please write your code here.
char[][] map = new char[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++) {
map[i][j] = arr[i].charAt(j);
}
}
int dy[] = {1,0,-1,0,-1,-1,1,1};
int dx[] = {0,1,0,-1,-1,1,-1,1};
int ans = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(map[i][j] != 'L') continue;
for(int dir = 0; dir < DIR_NUM; dir++) {
int cnt = 0;
for(int k = 1; k <= 2; k++) {
int y = i + dy[dir]*k;
int x = j + dx[dir]*k;
if(isOutOfBound(y,x,n,m)) break;
if(map[y][x] != 'E') break;
cnt++;
if(cnt == 2) {
ans++;
}
}
}
}
}
System.out.println(ans);
}
static boolean isOutOfBound(int y, int x, int n, int m) {
if(y < 0 || y >= n || x < 0 || x >= m) return true;
return false;
}
}
풀이2 구현
import java.util.Scanner;
public class Main {
public static final int DIR_NUM = 8;
public static final int MAX_N = 100;
public static int n, m;
public static String[] arr = new String[MAX_N];
public static int[] dx = new int[]{1, 1, 1, -1, -1, -1, 0, 0};
public static int[] dy = new int[]{-1, 0, 1, -1, 0, 1, -1, 1};
public static boolean inRange(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < m;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 입력
n = sc.nextInt();
m = sc.nextInt();
for(int i = 0; i < n; i++)
arr[i] = sc.next();
// 모든 칸을 시작 칸으로 삼아 여덟 방향을 모두 확인해봅니다.
int cnt = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
if(arr[i].charAt(j) != 'L') continue;
for(int k = 0; k < DIR_NUM; k++) {
int curt = 1;
int curx = i;
int cury = j;
while(true) {
int nx = curx + dx[k];
int ny = cury + dy[k];
if(inRange(nx, ny) == false)
break;
if(arr[nx].charAt(ny) != 'E')
break;
curt++;
curx = nx;
cury = ny;
}
if(curt >= 3) {
cnt++;
}
}
}
System.out.println(cnt);
}
}