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 | # »óŸ¦ ³ªÅ¸³»´Â Ŭ·¡½º 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 # °´Ã¼¸¦ Ãâ·ÂÇÒ ¶§ »ç¿ëÇÑ´Ù. def __str__(self): return 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 = [ ] open_queue.append(State(puzzle, goal)) closed_queue = [ ] moves = 0 while len(open_queue) != 0: # µð¹ö±ëÀ» À§ÇÑ ÄÚµå # print("START OF OPENQ") # for elem in open_queue.queue: # print(elem) # print("END OF OPENQ") current = open_queue.pop(0) # OPEN ¸®½ºÆ®ÀÇ ¾Õ¿¡¼ »èÁ¦ print(current) if current.board == goal: print("Ž»ö ¼º°ø") break moves = current.moves+1 closed_queue.append(current) for state in current.expand(moves): if (state in closed_queue) or (state in open_queue): # ÀÌ¹Ì °ÅÃÄ°£ ³ëµåÀ̸é continue # ³ëµå¸¦ ¹ö¸°´Ù. else: open_queue.append(state) # OPEN ¸®½ºÆ®ÀÇ ³¡¿¡ Ãß°¡ | cs |