[알고리즘문제]
[백준] 2210 : 숫자판 점프
whatezlife
2025. 2. 27. 14:33
숫자판 점프 성공다국어
한국어
시간 제한메모리 제한제출정답맞힌 사람정답 비율
2 초 | 128 MB | 11165 | 8204 | 6566 | 74.597% |
문제
5×5 크기의 숫자판이 있다. 각각의 칸에는 숫자(digit, 0부터 9까지)가 적혀 있다. 이 숫자판의 임의의 위치에서 시작해서, 인접해 있는 네 방향으로 다섯 번 이동하면서, 각 칸에 적혀있는 숫자를 차례로 붙이면 6자리의 수가 된다. 이동을 할 때에는 한 번 거쳤던 칸을 다시 거쳐도 되며, 0으로 시작하는 000123과 같은 수로 만들 수 있다.
숫자판이 주어졌을 때, 만들 수 있는 서로 다른 여섯 자리의 수들의 개수를 구하는 프로그램을 작성하시오.
입력
다섯 개의 줄에 다섯 개의 정수로 숫자판이 주어진다.
출력
첫째 줄에 만들 수 있는 수들의 개수를 출력한다.
예제 입력 1 복사
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1
예제 출력 1 복사
15
힌트
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112, 121211, 121212, 211111, 211121, 212111, 212121 이 가능한 경우들이다.
package 문제1926그림;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[][] arr;
static boolean[][] visited;
static int[] dirx = {-1, 1, 0, 0}; // 상하좌우
static int[] diry = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("res/문제1926그림.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
StringTokenizer st = new StringTokenizer(s);
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
arr = new int[N][M];
visited = new boolean[N][M];
for (int i = 0; i<N; i++) {
s = br.readLine();
st = new StringTokenizer(s);
for (int j = 0; j<M; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
} // 입력 받기
LinkedList<Integer> pictures = new LinkedList<>();
for (int i = 0; i<N; i++) {
for (int j = 0; j<M; j++) {
if (arr[i][j]==1 && visited[i][j]!=true) {
int n = bfs(i, j);
pictures.add(n);
}
}
}
Collections.sort(pictures, Collections.reverseOrder());
if (pictures.isEmpty()) {
System.out.println(0);
System.out.println(0);
} else {
System.out.println(pictures.size());
System.out.println(pictures.get(0));
}
br.close();
}
public static int bfs (int x, int y) {
int area = 0;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] {x, y});
visited[x][y] = true;
while(!queue.isEmpty()) {
area++;
int[] xy = queue.poll();
int curx = xy[0];
int cury = xy[1];
for (int i = 0; i<4; i++) {
if (curx+dirx[i] >=0 && curx+dirx[i]<arr.length && cury+diry[i] >=0 && cury+diry[i] < arr[0].length) {
if (arr[curx+dirx[i]][cury+diry[i]]==1 && visited[curx+dirx[i]][cury+diry[i]]!=true) {
queue.add(new int[] {curx+dirx[i],cury+diry[i]});
visited[curx+dirx[i]][cury+diry[i]]=true;
}
}
}
} // while문
return area;
}
}
지금까지 푼게 DFS가 아니라 BFS였다.
완벽하게 착각하고 두 개를 반대로 생각해서 풀고 있었다
DFS -> stack(이기때문에 거꾸로 저장) + 재귀함수 활용
BFS -> queue(순서대로 저장) + while 활용