배열의 복사

Structure of Knowledge·2021년 5월 14일
0

배열의 복사

// 얕은 복사
String[][] tempBoard = board;

// 깊은 복사
String[][] tempBoard = new String[N][M];
for(int i=0; i<N; i++){ 
	for(int j=0; j<M; j++){
    		tempBoard[i][j] = board[i][j];
        }
}
  1. 배열을 복사하기 위해 단순히 다음과 같이 복사한다면, tempBoard에 board의 참조값이 대입되므로, tempBoard의 배열 방의 값을 변경한다면 board 역시 바뀌게 된다.

  2. 두 번째 방법으로 해야 서로 다른 배열 객체가 된다.

백준 1018번 체스판 다시 칠하기.

  1. 8 * 8 체스판을 규칙에 맞게 바꾸고, 회수를 세는 메소드를 만든다.

  2. 규격이 큰 체스판에서 모든 경우에 1의 메소드를 호출하여 검사할 수 있도록 반복문을 작성한다.

  3. 카운트가 가장 작은 경우를 출력한다.(최솟값)

import java.io.*;

class Main1018 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] caseStr = br.readLine().split(" ");
        int N = Integer.parseInt(caseStr[0]);
        int M = Integer.parseInt(caseStr[1]);
        String[][] board = new String[N][M];
        for(int i=0; i<N; i++){ // 주어진 예시를 이차원 배열에 입력한다.
            String line = br.readLine();
            for(int j=0; j<M; j++){
                board[i][j] = line.substring(j,j+1);
            }
        }
        
        // 모든 경우를 검사하고 최소로 변경된 값을 출력한다.
        int answer = 9999;
        for(int i=0; i< N-7; i++){
            for(int j=0; j< M-7; j++){
                int temp = checkBoard(board, i, j, N, M);
                if(temp < answer) answer = temp;
            }
        }
        System.out.println(answer);
    }
    // 8*8을 검사하는 메소드 필요  
    static int checkBoard(String[][] board, int startI, int startJ, int N, int M){
        int endI = startI + 8;
        int endJ = startJ + 8;
        int count = 0;
         // tempBoard = board 로 정의하면 안된다... 참조값을 대입하므로 같은 객체가 되어버림.
        String[][] tempBoard = new String[N][M];
        for(int i=0; i<N; i++){ 
            for(int j=0; j<M; j++){
                tempBoard[i][j] = board[i][j];
            }
        }
        for(int i= startI; i< endI; i++){
            for(int j= startJ; j< endJ; j++){
                if(j == (endJ - 1)) break;
                if(tempBoard[i][j+1].equals(tempBoard[i][j])){
                    if(tempBoard[i][j].equals("B")) tempBoard[i][j+1] = "W";
                    else tempBoard[i][j+1] = "B";
                    count++;
                }    
            }
            if(i==(endI - 1)) break;
            if(tempBoard[i+1][startJ].equals(tempBoard[i][startJ])){
                if(tempBoard[i][startJ].equals("B")) tempBoard[i+1][startJ] = "W";
                else tempBoard[i+1][startJ] = "B";
                count++;
            }
        }
        // 첫번째 칸의 색깔을 바꾸어 칠하는 경우 == (64-count)
        count = Math.min(count, 64 - count);
        return count;
    }
}
profile
객체와 제어, 비전공자 개발자 되기

1개의 댓글

comment-user-thumbnail
2021년 5월 14일

오빠 멋져요bbbbbb

답글 달기