1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | import queue # »óŸ¦ ³ªÅ¸³»´Â Ŭ·¡½º, f(n) °ªÀ» ÀúÀåÇÑ´Ù. class State: def __init__(self, board, goal, moves=0): self.board = board self.moves = moves self.goal = goal # i1°ú i2¸¦ ±³È¯ÇÏ¿©¼ »õ·Î¿î »óŸ¦ ¹ÝȯÇÑ´Ù. def get_new_board(self, i1, i2, moves): new_board = self.board[:] new_board[i1], new_board[i2] = new_board[i2], new_board[i1] return State(new_board, self.goal, moves) # ÀÚ½Ä ³ëµå¸¦ È®ÀåÇÏ¿©¼ ¸®½ºÆ®¿¡ ÀúÀåÇÏ¿©¼ ¹ÝȯÇÑ´Ù. def expand(self, moves): result = [] i = self.board.index(0) # ¼ýÀÚ 0(ºóÄ)ÀÇ À§Ä¡¸¦ ã´Â´Ù. if not i in [0, 1, 2] : # UP ¿¬»êÀÚ result.append(self.get_new_board(i, i-3, moves)) if not i in [0, 3, 6] : # LEFT ¿¬»êÀÚ result.append(self.get_new_board(i, i-1, moves)) if not i in [2, 5, 8]: # DOWN ¿¬»êÀÚ result.append(self.get_new_board(i, i+1, moves)) if not i in [6, 7, 8]: # RIGHT ¿¬»êÀÚ result.append(self.get_new_board(i, i+3, moves)) return result # f(n)À» °è»êÇÏ¿© ¹ÝȯÇÑ´Ù. def f(self): return self.h()+self.g() # ÈÞ¸®½ºÆ½ ÇÔ¼ö °ªÀÎ h(n)À» °è»êÇÏ¿© ¹ÝȯÇÑ´Ù. # ÇöÀç Á¦ À§Ä¡¿¡ ÀÖÁö ¾ÊÀº ŸÀÏÀÇ °³¼ö¸¦ ¸®½ºÆ® ÇÔÃàÀ¸·Î °è»êÇÑ´Ù. def h(self): return sum([1 if self.board[i] != self.goal[i] else 0 for i in range(8)]) # ½ÃÀÛ ³ëµå·ÎºÎÅÍÀÇ °æ·Î¸¦ ¹ÝȯÇÑ´Ù. def g(self): return self.moves def __eq__(self, other): return self.board == other.board # »óÅÂ¿Í »óŸ¦ ºñ±³Çϱâ À§ÇÏ¿© less than ¿¬»êÀÚ¸¦ Á¤ÀÇÇÑ´Ù. def __lt__(self, other): return self.f() < other.f() def __gt__(self, other): return self.f() > other.f() # °´Ã¼¸¦ Ãâ·ÂÇÒ ¶§ »ç¿ëÇÑ´Ù. def __str__(self): return "------------------ f(n)=" + str(self.f()) +"\n"+\ "------------------ h(n)=" + str(self.h()) +"\n"+\ "------------------ g(n)=" + str(self.g()) +"\n"+\ str(self.board[:3]) +"\n"+\ str(self.board[3:6]) +"\n"+\ str(self.board[6:]) +"\n"+\ "------------------" # Ãʱ⠻óÅ puzzle = [1, 2, 3, 0, 4, 6, 7, 5, 8] # ¸ñÇ¥ »óÅ goal = [1, 2, 3, 4, 5, 6, 7, 8, 0] # open ¸®½ºÆ®´Â ¿ì¼±¼øÀ§ Å¥·Î »ý¼ºÇÑ´Ù. open_queue = queue.PriorityQueue() open_queue.put(State(puzzle, goal)) closed_queue = [ ] moves = 0 while not open_queue.empty(): # µð¹ö±ëÀ» À§ÇÑ ÄÚµå # print("START OF OPENQ") # for elem in open_queue.queue: # print(elem) # print("END OF OPENQ") current = open_queue.get() print(current) if current.board == goal: print("Ž»ö ¼º°ø") break moves = current.moves+1 for state in current.expand(moves): if state not in closed_queue: open_queue.put(state) closed_queue.append(current) else: print ('Ž»ö ½ÇÆÐ') | cs |