문제(출처: https://www.acmicpc.net/problem/3005)
< 크로스워드 퍼즐 쳐다보기 >
문제 풀이
가로, 세로를 살펴보며 낱말을 만들어 정렬한다.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class _3005_ { // 크로스워드 퍼즐 쳐다보기
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
char[][] arr = new char[r][c];
for (int i = 0; i < r; i++) {
String str = bf.readLine();
for (int j = 0; j < c; j++) {
arr[i][j] = str.charAt(j);
}
}
ArrayList<String> result = new ArrayList<>();
// 가로
for (int i = 0; i < r; i++) {
String str = "";
for (int j = 0; j < c; j++) {
if (arr[i][j] != '#') {
str += arr[i][j];
} else {
if (str.length() > 1) {
result.add(str);
}
str = "";
}
}
if (str.length() > 1) {
result.add(str);
}
}
// 세로
for (int i = 0; i < c; i++) {
String str = "";
for (int j = 0; j < r; j++) {
if (arr[j][i] != '#') {
str += arr[j][i];
} else {
if (str.length() > 1) {
result.add(str);
}
str = "";
}
}
if (str.length() > 1) {
result.add(str);
}
}
Collections.sort(result);
System.out.println(result.get(0));
}
}
변수)
r, c : 퍼즐의 크기
arr : 퍼즐 정보
result : 만들 수 있는 단어
퍼즐의 크기를 입력받는다. 퍼즐의 크기만큼 퍼즐의 정보를 입력받아 arr 배열에 저장한다. 먼저 가로를 살펴보며 단어를 찾아 result에 저장한다. 그다음 세로를 살펴보며 단어를 찾아 result에 저장한다. result를 정렬한 후 사전순으로 제일 앞서는 단어를 출력한다.
'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글
[Baekjoon] 1124_언더프라임 (1) | 2024.02.26 |
---|---|
[Baekjoon] 2232_지뢰 (0) | 2024.02.23 |
[Baekjoon] 1706_크로스워드 (0) | 2024.02.20 |
[Baekjoon] 11437_LCA (0) | 2024.02.19 |
[Baekjoon] 8911_거북이 (1) | 2024.02.16 |