코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Solution_2819 {
private static HashSet<String> hs;
private static char[][] m;
public static class Point{
int x, y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
StringBuilder sb = new StringBuilder();
int tc =Integer.parseInt(st.nextToken());
for(int t = 1; t <= tc; t++ ) {
m = new char[4][4];
for (int i = 0; i < 4; i++) {
String s = br.readLine();
for (int j = 0, index = 0; j < 4; j++, index+=2) {
m[i][j] = s.charAt(index);
}
}
hs = new HashSet<>();
for(int r = 0; r < 4; r++) {
for(int c =0; c <4; c++) {
go(r,c,1,"");
}
}
sb.append("#").append(tc).append(" ").append(hs.size()).append("\n");
}
System.out.println(sb.toString());
}
public static int dx[] = {0, 1, 0, -1};
public static int dy[] = {1, 0, -1, 0};
private static void go(int r, int c, int step, String str) {
if(r < 0 || r >= 4 || c < 0 || c >= 4) return;
str += m[r][c];
if(step == 7) {
if(!hs.contains(str)) {
hs.add(str);
}
return;
}
for(int i = 0; i < dx.length; i++) {
go(r + dx[i], c + dy[i], step +1, str);
}
}
}
수정한 코드
- String으로 이어 붙이는 코드보다 메모리를 줄이기 위해 수정함
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Solution_2819_이광용 {
private static HashSet<Integer> hs;
private static int[][] m;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
StringBuilder sb = new StringBuilder();
int tc =Integer.parseInt(st.nextToken());
for(int t = 1; t <= tc; t++ ) {
m = new int[4][4];
for (int i = 0; i < 4; i++) {
String s = br.readLine();
for (int j = 0, index = 0; j < 4; j++, index+=2) {
m[i][j] = s.charAt(index) - '0';
}
}
hs = new HashSet<>();
for(int r = 0; r < 4; r++) {
for(int c =0; c <4; c++) {
go(r,c,1, 0);
}
}
sb.append("#").append(t).append(" ").append(hs.size()).append("\n");
}
System.out.println(sb.toString());
}
public static int dx[] = {0, 1, 0, -1};
public static int dy[] = {1, 0, -1, 0};
private static void go(int r, int c, int step, int num) {
if(r < 0 || r >= 4 || c < 0 || c >= 4) return;
num = num *10 + m[r][c];
if(step == 7) {
if(!hs.contains(num)) {
hs.add(num);
}
return;
}
for(int i = 0; i < dx.length; i++) {
go(r + dx[i], c + dy[i], step +1, num);
}
}
}