[JAVA-자바] 15686번: 치킨 배달

2025. 4. 25. 23:40·알고리즘/백준

 

소스코드:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    static class Pos {
        private int y;
        private int x;

        Pos(int y, int x) {
            this.y = y;
            this.x = x;
        }
    }

    static BufferedReader br;
    static BufferedWriter bw;

    static int N;
    static int M;
    static int[][] board;

    static List<Pos> homeList;
    static List<Pos> chickenList;

    public static List<List<Pos>> selectChickens() {
        List<List<Pos>> result = new ArrayList<>();
        List<Pos> selected = new ArrayList<>();
        backtracking(0, selected, result);
        return result;
    }

    public static void backtracking(int start, List<Pos> selected, List<List<Pos>> result) {
        if (selected.size() >= 1 && selected.size() <= M) {
            result.add(new ArrayList<>(selected));
        }

        if (selected.size() == M) {
            return;
        }

        for (int i = start; i < chickenList.size(); i++) {
            selected.add(chickenList.get(i));
            backtracking(i + 1, selected, result);
            selected.remove(selected.size() - 1);
        }
    }

    public static int getChickenDistance(List<Pos> selectChickens) {
        int sum = 0;

        for (Pos homePos : homeList) {
            int minDistance = Integer.MAX_VALUE;

            for (Pos chickenPos : selectChickens) {
                int calc = Math.abs(chickenPos.y - homePos.y) + Math.abs(chickenPos.x - homePos.x);
                minDistance = Math.min(minDistance, calc);
            }
            sum += minDistance;
        }

        return sum;
    }

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        bw = new BufferedWriter(new OutputStreamWriter(System.out));

        homeList = new ArrayList<>();
        chickenList = new ArrayList<>();

        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        board = new int[N + 1][N + 1];

        for (int y = 1; y <= N; y++) {
            st = new StringTokenizer(br.readLine());
            for (int x = 1; x <= N; x++) {
                board[y][x] = Integer.parseInt(st.nextToken());
                if (board[y][x] == 1) {
                    homeList.add(new Pos(y, x));
                } else if (board[y][x] == 2) {
                    chickenList.add(new Pos(y, x));
                }
            }
        }
        br.close();

        int minDistance = Integer.MAX_VALUE;
        for (List<Pos> selectedChickedList : selectChickens()) {
            int calc = getChickenDistance(selectedChickedList);
            minDistance = Math.min(minDistance, calc);
        }

        bw.write(minDistance + "\n");
        bw.close();
    }
}

 

글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.

여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.

'알고리즘 > 백준' 카테고리의 다른 글

[JAVA-자바] 1043번: 거짓말  (0) 2025.04.30
[JAVA-자바] 17070번: 파이프 옮기기 1  (0) 2025.04.29
[JAVA-자바] 11003번: 최솟값 찾기  (0) 2025.04.24
[JAVA-자바] 13549번: 숨바꼭질 3  (0) 2025.04.23
[JAVA-자바] 12865번: 평범한 배낭  (0) 2025.04.23
'알고리즘/백준' 카테고리의 다른 글
  • [JAVA-자바] 1043번: 거짓말
  • [JAVA-자바] 17070번: 파이프 옮기기 1
  • [JAVA-자바] 11003번: 최솟값 찾기
  • [JAVA-자바] 13549번: 숨바꼭질 3
raven
raven
Github : https://github.com/RabeMaster | Email : ra___be@naver.com
  • raven
    배움을 원하는 사람
    raven
  • 전체
    오늘
    어제
  • 공지사항

    • 안녕하세요
    • 분류 전체보기 (169)
      • 네이버 부스트캠프 10기 (7)
        • 멤버십 (5)
        • 챌린지 (1)
        • 베이직 (1)
      • 공부 (2)
        • JAVA (1)
        • CS (0)
        • 정보처리기사 (1)
      • 알고리즘 (159)
        • 백준 (159)
      • 개발 (1)
        • 백준 확장 프로그램 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 인기 글

  • 태그

    백트래킹
    너비 우선 탐색
    멤버십
    네이버부스트캠프
    자료 구조
    그래프 이론
    네부캠
    정렬
    최단 경로
    그리디 알고리즘
    스택
    브루트포스 알고리즘
    회고
    알고리즘
    네이버
    수학
    개발
    코딩
    코테
    문자열
    백준
    부트캠프
    그래프 탐색
    구현
    코딩테스트
    자바
    IT
    다이나믹 프로그래밍
    부스트캠프
    java
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
raven
[JAVA-자바] 15686번: 치킨 배달
상단으로

티스토리툴바