코딩테스트

JAVA 코테 준비 - softeer 나무 공격

yolang 2024. 11. 19. 22:32
728x90

 

어우 여러 언어로 코테 준비 하려고 하니, input 부터 막힌다...

가볍게 몸풀겸 쉬운 문제 하나

 

input 은 bufferedReader를 사용한다. 

근데 꼭 try, catch문을 써야 에러가 안뜬다. 

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        try{
        	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            String input = bf.readLine();
            System.out.println(input);
        } catch (IOException e){
        System.out.println(e);
        }
    }
}

 

리스트 선언

List<Integer> row = new ArrayList<>();

 

최종 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String[] input = br.readLine().split(" ");
            int n = Integer.parseInt(input[0]);
            int m = Integer.parseInt(input[1]);
            int total = 0;
            List<List<Integer>> board = new ArrayList<>();

            for (int i = 0; i < n; i++) {
                List<String> row = List.of(br.readLine().split(" "));
                List<Integer> row_inst = new ArrayList<>();
                for (String s : row) {
                    int s_int = Integer.parseInt(s);
                    if (s_int == 1) total ++;
                    row_inst.add(s_int);
                }
                board.add(row_inst);
            }
            for (int i = 0; i < 2; i++) {
                String[] attackCounts = br.readLine().split(" ");
                int first = Integer.parseInt(attackCounts[0]) - 1;
                int second = Integer.parseInt(attackCounts[1]) - 1;
                total = total - attack(first, second, board);
            }

        System.out.println(total);

        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private static int attack(int first, int second, List<List<Integer>> board) {
        int killed = 0;
        for (int i = first; i <= second; i++) {
            for (int j = 0; j < board.get(i).size(); j++) {
                if (board.get(i).get(j) == 1) {
                    board.get(i).set(j, 0);
                    killed += 1;
                    break;
                }
            }
        }
        return killed;
    }
}
728x90