- 생각
가로,세로로 인접한 7명의 학생중 이다솜파가 4명이상 있을 수 있는 수를 출력하면 되는 문제이다.
dfs를 통해 basecase를 7명학생으로하고 7명 학생 중 4명이상이 이다솜파이면 count를 증가시키는 식으로 하면될 것 같다. (배열을 돌 때 인접한 7명을 상하좌우로 반복문을 돌리면서 찾으니 모든 7명의 경우의 수를 찾지 않게된다.)
- 코드
정답 코드 : 백트래킹을 이용해 풀었다. 배열을 돌리는 과정을 나중에 한번 더 공부하면 좋을 듯
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int answer;
static char[][] array;
static boolean[] check;
static int[] x = { -1, 0, 1, 0 };
static int[] y = { 0, -1, 0, 1 };
public static void main(String[] args) throws Exception {
SetData();
System.out.println(answer);
}
private static void SetData() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
answer = 0;
array = new char[5][5];
check = new boolean[1 << 25];
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < 5; i++) {
String s = br.readLine();
for (int j = 0; j < 5; j++) {
array[i][j] = s.charAt(j);
if (array[i][j] == 'S')
queue.offer(new int[] { i, j });
}
}
while (!queue.isEmpty()) {
int location[] = queue.poll();
check[1 << (location[0] * 5 + location[1])] = true;
dfs(1, 1, 1 << (location[0] * 5 + location[1]));
}
}
private static void dfs(int count, int lee, int mark) {
// basecase
if (count == 7) {
if (lee >= 4) {
answer++;
}
return;
}
for (int i = 0; i < 25; i++) {
if ((mark & (1 << i)) == 0)
continue; // 현재 경로찾기
for (int k = 0; k < 4; k++) {
int r = i / 5 + x[k];
int c = i % 5 + y[k];
if (r < 0 || r >= 5 || c < 0 || c >= 5) continue;
int number = r * 5 + c;
if (check[mark | (1 << number)]) continue; // 이미 방문했다면
check[mark | (1 << number)] = true;
if (array[r][c] == 'S')
dfs(count + 1, lee + 1, mark | (1 << (number)));
if (array[r][c] == 'Y')
dfs(count + 1, lee, mark | (1 << (number)));
}
}
}
}
반복문 돌리는 방법을 배운 곳
'algorithm' 카테고리의 다른 글
[BOJ/JAVA] 백준 1339번 : 단어 수학 (0) | 2021.01.04 |
---|---|
[BOJ/JAVA] 백준 2448번 : 별찍기 - 11 (0) | 2020.12.24 |
[JAVA] 백준(BOJ) 9466번 : 텀 프로젝트 (0) | 2020.12.23 |
[JAVA] 백준 2583번 : 영역 구하기 (0) | 2020.12.22 |
[JAVA] 백준 2302번 : 극장 좌석 (0) | 2020.12.22 |