-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.js
More file actions
102 lines (86 loc) · 2.63 KB
/
Copy path1.js
File metadata and controls
102 lines (86 loc) · 2.63 KB
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
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const input = [];
rl.on("line", (line) => {
input.push(line);
if (input.length > 1 && input.length === parseInt(input[0]) + 1) {
rl.close();
}
});
rl.on("close", () => {
const N = parseInt(input[0]);
const map = [];
for (let i = 1; i < N + 1; i++) {
map.push(input[i].split('').map(char => colorToInt[char]));
}
const result = solution(N, map);
console.log(result);
process.exit();
});
const colorToInt = {
'C': 1,
'P': 2,
'Z': 3,
'Y': 4
};
function solution(N, map) {
let maxCount = 0;
// 현재 상태의 최대 연속 길이 확인
maxCount = Math.max(maxCount, checkMaxConsecutive(map, N));
// 모든 인접한 두 사탕을 교환해보고 최대 연속 길이 확인
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
// 오른쪽과 교환
if (j + 1 < N && map[i][j] !== map[i][j + 1]) {
// 교환
[map[i][j], map[i][j + 1]] = [map[i][j + 1], map[i][j]];
// 최대 연속 길이 확인
maxCount = Math.max(maxCount, checkMaxConsecutive(map, N));
// 원래대로 복구
[map[i][j], map[i][j + 1]] = [map[i][j + 1], map[i][j]];
}
// 아래쪽과 교환
if (i + 1 < N && map[i][j] !== map[i + 1][j]) {
// 교환
[map[i][j], map[i + 1][j]] = [map[i + 1][j], map[i][j]];
// 최대 연속 길이 확인
maxCount = Math.max(maxCount, checkMaxConsecutive(map, N));
// 원래대로 복구
[map[i][j], map[i + 1][j]] = [map[i + 1][j], map[i][j]];
}
}
}
return maxCount;
}
// 전체 보드에서 최대 연속 길이 확인
function checkMaxConsecutive(map, N) {
let maxLength = 1;
// 행 방향 확인
for (let i = 0; i < N; i++) {
let count = 1;
for (let j = 1; j < N; j++) {
if (map[i][j] === map[i][j - 1]) {
count++;
} else {
count = 1;
}
maxLength = Math.max(maxLength, count);
}
}
// 열 방향 확인
for (let j = 0; j < N; j++) {
let count = 1;
for (let i = 1; i < N; i++) {
if (map[i][j] === map[i - 1][j]) {
count++;
} else {
count = 1;
}
maxLength = Math.max(maxLength, count);
}
}
return maxLength;
}