[SWEA] 2819 격자판의 숫자 이어 붙이기

Time Lapse :NONE

2819.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import java.io.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Solution {
static Set<Integer>[][][] dp = new Set[4][4][7];
static int[][] map = new int[4][4];
static int[] dx = {0, 1, 0, -1};
static int[] dy = {-1, 0, 1, 0};
static int TC, t, ans;
static Reader r = new Reader();
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
TC = r.nextInt();
for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j)
for(int k = 0; k < 7; ++k)
dp[i][j][k] = new HashSet<>();
while(TC--!=0){
for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j){
map[i][j] = r.nextInt();
for(int k = 0; k < 7; ++k)
dp[i][j][k].clear();
}

ans = 0;

for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j) {
ans += solution(i, j, map[i][j], 0);
}
bw.write("#" + ++t + " " + ans + "\n");
}
bw.flush();
}
static int solution(int y, int x, int val, int c){
if(dp[y][x][c].contains(val))
return 0;
if(c == 6) {
for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j)
dp[i][j][c].add(val);
return 1;
}
dp[y][x][c].add(val);
int ret = 0;
for(int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if(0 <= nx && nx < 4 && 0 <= ny && ny < 4)
ret += solution(ny, nx, val * 10 + map[ny][nx], c + 1);
}
return ret;
}

static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public int nextInt() throws IOException {
int ret = 0, flag = 1;
byte c = read();
if(c == '-') {
flag = -1;
c = read();
}
do {
ret = (ret<<3) + (ret<<1) + (c & 0b1111);
} while ((c = read()) >= '0' && c <= '9');

return ret * flag;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}


private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/07/PS/SWEA/2819/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.