Skip to content

Commit 3e7b485

Browse files
committed
[Silver I] Title: 행렬, Time: 160 ms, Memory: 16548 KB -BaekjoonHub
1 parent 2913224 commit 3e7b485

File tree

2 files changed

+118
-0
lines changed

2 files changed

+118
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Silver I] 행렬 - 1080
2+
3+
[문제 링크](https://www.acmicpc.net/problem/1080)
4+
5+
### 성능 요약
6+
7+
메모리: 16548 KB, 시간: 160 ms
8+
9+
### 분류
10+
11+
그리디 알고리즘
12+
13+
### 제출 일자
14+
15+
2025년 10월 29일 09:58:20
16+
17+
### 문제 설명
18+
19+
<p>0과 1로만 이루어진 행렬 A와 행렬 B가 있다. 이때, 행렬 A를 행렬 B로 바꾸는데 필요한 연산의 횟수의 최솟값을 구하는 프로그램을 작성하시오.</p>
20+
21+
<p>행렬을 변환하는 연산은 어떤 3×3크기의 부분 행렬에 있는 모든 원소를 뒤집는 것이다. (0 → 1, 1 → 0)</p>
22+
23+
### 입력
24+
25+
<p>첫째 줄에 행렬의 크기 N M이 주어진다. N과 M은 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 행렬 A가 주어지고, 그 다음줄부터 N개의 줄에는 행렬 B가 주어진다.</p>
26+
27+
### 출력
28+
29+
<p>첫째 줄에 문제의 정답을 출력한다. 만약 A를 B로 바꿀 수 없다면 -1을 출력한다.</p>
30+
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
static int [][] arr1;
7+
static int [][] arr2;
8+
static int N,M;
9+
public static void main(String[] args) throws Exception {
10+
11+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
13+
StringTokenizer st = new StringTokenizer(br.readLine());
14+
15+
N = Integer.parseInt(st.nextToken());
16+
17+
M = Integer.parseInt(st.nextToken());
18+
19+
arr1 = new int[N][M];
20+
21+
for(int i =0; i < N; i++) {
22+
String input = br.readLine();
23+
for(int j =0; j<input.length(); j++) {
24+
arr1[i][j] = Integer.parseInt(input.charAt(j) + "");
25+
}
26+
}
27+
28+
arr2 = new int[N][M];
29+
for(int i =0; i < N; i++) {
30+
String input = br.readLine();
31+
for(int j =0; j<input.length(); j++) {
32+
arr2[i][j] = Integer.parseInt(input.charAt(j) + "");
33+
}
34+
}
35+
if(isSameMetric()) {
36+
System.out.println(0);
37+
System.exit(0);
38+
}
39+
40+
if(N < 3 || M <3) {
41+
System.out.println(-1);
42+
System.exit(0);
43+
}
44+
int count = 0;
45+
for(int i =0; i<N-2; i++) {
46+
for(int j =0; j<M-2; j++) {
47+
if(arr1[i][j] != arr2[i][j]) {
48+
change(i,j);
49+
count+=1;
50+
}
51+
52+
if(isSameMetric()) {
53+
System.out.println(count);
54+
System.exit(0);
55+
}
56+
57+
}
58+
}
59+
if(isSameMetric()) {
60+
System.out.println(count);
61+
System.exit(0);
62+
}
63+
System.out.println(-1);
64+
}
65+
66+
private static void change(int x, int y) {
67+
for(int i = x; i< x+3; i++) {
68+
for(int j = y; j< y+3; j ++) {
69+
if(arr1[i][j] == 0) {
70+
arr1[i][j] = 1;
71+
} else {
72+
arr1[i][j] = 0;
73+
}
74+
}
75+
}
76+
}
77+
78+
private static boolean isSameMetric() {
79+
for(int i = 0; i< N; i++) {
80+
for(int j = 0; j< M; j ++) {
81+
if(arr1[i][j] != arr2[i][j]) {
82+
return false;
83+
}
84+
}
85+
}
86+
return true;
87+
}
88+
}

0 commit comments

Comments
 (0)