백준 1080번 행렬

이상민·2024년 1월 12일
0

알고리즘

목록 보기
122/128
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Matrix {

    static int N;
    static int M;
    static int[][] A;
    static int[][] B;
    static boolean[][] visited;
    static int count = 0;
    static int answer = 0;
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st= new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        A = new int[N][M];
        B = new int[N][M];

        for (int i = 0; i < N; i++) {
            String str = br.readLine();
            for (int j = 0; j < M; j++) {
                A[i][j] = str.charAt(j)-'0';
            }
        }
        for (int i = 0; i < N; i++) {
            String str = br.readLine();
            for (int j = 0; j < M; j++) {
                B[i][j] = str.charAt(j)-'0';
            }
        }
        for (int i = 0; i <N ; i++) {
            for (int j = 0; j <M ; j++) {
                if(i+2>=N||j+2>=M) continue;
                check(i,j);

            }
        }
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if(A[i][j]==B[i][j]) {
                    count++;
                }
            }
        }
        if(count==N*M){
            System.out.println(answer);
        }
        else {
            System.out.println(-1);
        }
    }
    public static void check(int row, int col) {
        if(A[row][col]!=B[row][col]){
            flip(row,col);
            answer++;
        }

    }
    public static void flip(int row, int col) {

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if(A[row+i][col+j]==0) {
                    A[row+i][col+j] = 1;
                }
                else {
                    A[row+i][col+j] = 0;
                }


            }

        }

    }

}

풀이방법

📢이 문제의 핵심은 3x3의 행렬에 가장왼쪽 위부분을 반복해서 뒤집지 않는것이다. 반복해서 뒤집어 봐야 0,1만 나오므로 동일한 B좌표와 같도록 최대 한번까지만 뒤집는다.
A[row][col] != B[row][col] 이라면 뒤집고, 같다면 넘어간다.
A[row][col] 좌표를 확정시키고, 다음 좌표를 탐색한다.

이런식으로 3x3행렬을 확인하여, 중복을 없앤다.

후기

아니 알면 간단한데, 풀때는 전혀안보인다...

profile
개린이

0개의 댓글