[SWEA D3] 1220. [S/W 문제해결 기본] 5일차 - Magnetic : JAVA풀이

김민주·2022년 11월 18일
0

문제 - 1220. [S/W 문제해결 기본] 5일차 - Magnetic

swexpertacademy 문제 바로가기 (로그인 후 이용가능)



설명

자석의 움직임을 모두 구현해서 푸는 것보다 규칙을 알면 풀 수 있는 문제이다.

교착개수가 되기 위해서는

입력받는 1(빨간 N극 자성체), 2(파란 S극 자성체)중 열 기준 순서대로 1->2가 오는 쌍의 개수와 일치한다.

  1. 첫번째 열부터 돌면서 1인 경우 1을 체크해주고 2를 초기화 시킨다.
  2. 2인 경우 blue변수를 체크해준다.
  3. red와 blue변수가 둘 다 1인 경우 교착개수의 개수를 증가시키고 초기화시킨다.



자바 풀이

import java.util.Scanner;

class Solution {


    public static void main(String args[]) throws Exception {

        Scanner sc = new Scanner(System.in);
        int T;
        T = 10;
        StringBuffer sb = new StringBuffer();
        int result;
        for (int test_case = 1; test_case <= T; test_case++) {

            result = 0; //교착 개수
            int n = sc.nextInt(); //100받기
            int[][] arr = new int[n][n];

            // 1 빨강: N극 자성체, 2: 파랑 S극 자성체
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    arr[i][j] = sc.nextInt();
                }
            }

            for(int i=0;i<n;i++){
                int red = 0;
                int blue =0;
                for(int j=0;j<n;j++){
                    if(arr[j][i] ==1){
                        red =1;
                        blue = 0;
                    }else if(arr[j][i] ==2){
                        blue =1;
                    }else{ }//0인경우

                    if(blue == 1 && red ==1) {result++; blue = red = 0;} //교착개수 증가
                }
            }

            sb.append("#").append(test_case).append(" ").append(result).append("\n");
        }

        System.out.println(sb);
    }

}
profile
𝐃𝐨𝐧'𝐭 𝐛𝐞 𝐚 𝐩𝐫𝐨𝐜𝐫𝐚𝐬𝐭𝐢𝐧𝐚𝐭𝐨𝐫💫

0개의 댓글