ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[๋ฐฑ์ค€ 15686] ์น˜ํ‚จ ๋ฐฐ๋‹ฌ (Python)

์€์ง„ 2021. 8. 10. 21:56

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[๋ฐฑ์ค€ 15686] ์น˜ํ‚จ ๋ฐฐ๋‹ฌ (Python)
๋ฐฑ์ค€


โœ๏ธIdea Sketch

2021-08-10

1. ์ถœ๋ ฅ๊ฐ’ ๋ถ„์„ํ•˜๊ธฐ

  • ์น˜ํ‚จ๊ฑฐ๋ฆฌ : ์ง‘๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์น˜ํ‚จ์ง‘ ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ
  • ์ง‘ (x1, y1), ์น˜ํ‚จ์ง‘ (x2, y2) ์ผ ๋•Œ, ์น˜ํ‚จ๊ฑฐ๋ฆฌ๋Š” |x1-x2| + |y1-y2| ์ด๋‹ค.
  • ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ : ๋ชจ๋“  ์น˜ํ‚จ๊ฑฐ๋ฆฌ์˜ ํ•ฉ
  • ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ์˜ ์ตœ์†Ÿ๊ฐ’์€?

2. ์ž…๋ ฅ๊ฐ’ ๋ถ„์„ํ•˜๊ธฐ

  • ๋„์‹œ์˜ ํฌ๊ธฐ๋Š” n*n ์ด๋‹ค.
  • ์น˜ํ‚จ์ง‘์€ m๊ฐœ ๋นผ๊ณ  ๋‹ค ํ์—…ํ•  ์˜ˆ์ •์ด๋‹ค.
  • 0์€ ๋นˆ์นธ์ด๋‹ค.
  • 1์€ ์ง‘์ด๋‹ค.
  • 2๋Š” ์น˜ํ‚จ์ง‘์ด๋‹ค.

3. ๋กœ์ง ์‚ดํŽด๋ณด๊ธฐ

  • ์น˜ํ‚จ์ง‘์ด 5๊ฐœ๊ณ , m์ด 2์ธ ๊ฒฝ์šฐ
  • ์น˜ํ‚จ์ง‘ 5๊ฐœ ์ค‘์— 2๊ฐœ๋ฅผ ๊ณ ๋ฅด๋Š” ๋ชจ๋“  ์กฐํ•ฉ์„ combinations ๋กœ ๊ตฌํ•œ๋‹ค.
  • city_length()์—์„œ ์น˜ํ‚จ๊ฑฐ๋ฆฌ min_length ์™€ ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ total์„ ๊ตฌํ•œ๋‹ค.
  • ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ์˜ ์ตœ์†Ÿ๊ฐ’ result ๋ฅผ ๊ตฌํ•œ๋‹ค.


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-08-10 356ms ํ†ต๊ณผ

import sys
from itertools import combinations

def city_length(shops):
  total = 0
  for house_x, house_y in houses:
    min_length = sys.maxsize
    for shop_x, shop_y in shops:
      length = abs(house_x - shop_x) + abs(house_y - shop_y)
      min_length = min_length if min_length < length else length
    total += min_length
  return total

if __name__ == '__main__':
  n, m = map(int, input().split())

  houses = []
  shops = []
  for i in range(n):
    line = input().split()
    for j in range(n):
      if line[j] == '1':
        houses.append([i, j])
      elif line[j] == '2':
        shops.append([i, j])

  result = sys.maxsize
  for shops in list(combinations(shops, m)):
    total = city_length(shops)
    result = result if result < total else total
  print(result)