728x90
코드
import java.io.*;
import java.util.Arrays;
public class Main {
static int n, m;
static Line[][] map;
static class Line {
int row;
int column;
public Line(int row, int column) {
this.row = row;
this.column = column;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int[] line = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
n = line[0]; m = line[1];
map = new Line[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) map[i][j] = new Line(0, 0);
}
for (int i = 0; i < m; i++) {
String[] s = br.readLine().split(" ");
int y = Integer.parseInt(s[0]) - 1, x = Integer.parseInt(s[1]) - 1;
drawLine(y, x, s[2]);
}
long cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cnt += (long) map[i][j].row * map[i][j].column;
}
}
bw.write(Long.toString(cnt));
bw.flush();
}
private static void drawLine(int y, int x, String dir) {
switch (dir)
{
case "L" :
for (int i = 0; i <= x; i++) map[y][i].row++;
break;
case "R":
for (int i = x; i < n; i++) map[y][i].row++;
break;
case "U":
for (int i = 0; i <= y; i++) map[i][x].column++;
break;
case "D":
for (int i = y; i < n; i++) map[i][x].column++;
break;
}
}
}
코드 설명
교차점은 '가로 선과 세로 선이 둘 다 존재할 경우' 생긴다.
따라서 Line이라는 클래스를 원소로 하는 2차원 배열을 선언하고 각 칸에 대한 가로 선과 세로 선의 개수를 따로 저장해두었다.
가로 선이 3개이고 세로 선이 2개 일 때 교차점은 3 * 2 = 6이다.
따라서 교차점의 개수는 '가로 선 * 세로 선'이다.
전에 풀었던 문제에서 했던 실수를 또 했는데 가로 선과 세로 선을 곱할 때 int형을 넘어갈 수 있다는 것이다.
마찬가지로 계산 식을 저장하는 변수만 long으로 설정했는데, 계산 식도 (long)으로 형변환하거나 가로 선과 세로 선의 개수를 long으로 저장하는 방법이 있다.
728x90
'코딩테스트 > Goorm' 카테고리의 다른 글
[구름톤 챌린지] 4-5. 연결 요소 제거하기 (0) | 2023.09.08 |
---|---|
[구름톤 챌린지] 4-4. 대체 경로 (0) | 2023.09.07 |
[구름톤 챌린지] 4-2. 통신망 분석 (0) | 2023.09.05 |
[구름톤 챌린지] 4-1. 연합 (0) | 2023.09.05 |
[구름톤 챌린지] 3-5. 과일 구매 (0) | 2023.09.01 |