简体   繁体   English

骑士之旅中的堆栈实现

[英]stack implementation in knight tour

A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once.骑士之旅是一个骑士在棋盘上的一系列移动,这样骑士恰好访问每个方格一次。 Standard chess rules apply.适用标准国际象棋规则。 A knight can move two squares in one direction and one square either horizontally or vertically, in either order.骑士可以在一个方向上移动两个方格,在水平或垂直方向上移动一个方格,顺序不限。 Given an integer n, find a knight's tour of an nxn chessboard给定一个 integer n,找到一个 nxn 棋盘的骑士之旅

#Here first we defined a stack class for use in KnightRoute class
'''The time complexity of this programm is O(8^n^2)'''
class Stack:

    def __init__(self):
        self.array = []    # define a empty list
        self.size = 0

    def push(self, element):
        self.array.append(element)                   #here we defined a push function for stack
        self.size += 1

    def pop(self):
        if self.size < 1:                        # here we defined a Pop function for stack
            print("No element to pop")
        else:
            self.size -= 1
            return self.array.pop(-1)

    def top(self):                        # here we defined a top function for stack for top element in stack
        if self.size < 1:
            return ""
        return self.array[-1]



def KnightsRoute(n):           # Make a KnightRoute class for our problem

    # Stack to keep track of moves that we are considering as solution
    moves = Stack()

    # Directions in which a knight can move
    directions = [[2, 1],[2, -1],[-2, 1],[-2, -1],[1, 2],[-1, 2],[1, -2],[-1, -2],]

     # Here we make a list of lists with False element visited or not
    vis = [[False for i in range(n)] for j in range(n)]

    # 2-D array to tell as the time at which we reached that particular cell
    graph = [[0 for i in range(n)] for j in range(n)]

    # Checking validity of a current move, current move should place knight somewhere inside the chessboard and that cell should be unvisited before we place knight in it
    def available(i, j):
        return i < n and j < n and i > -1 and j > -1 and not vis[i][j]

    # DFS on a cell to all possible moves and checking whether it would lead to a solution
    # si, sj are the coordinates of the current cell we will DFS from
    # cur is varibale to tell us how many cells are visited before this one
    def dfs(si, sj, cur=1):
        global ans

        # If the cells visited are equal to the number of cells in the chessboard, then we have in fact visited all cells and reached a solution
        if cur >= n * n:
            ans = True

        # Marking current cell as visited and pushing it in the solution stack
        vis[si][sj] = True
        moves.push((si, sj))

        # Calculating all other reachable cells from the current cell
        for a in directions:
            i = si + a[0]
            j = sj + a[1]

            # If current cell is valid, the we will DFS from it 
            if available(i, j):
                dfs(i, j, cur + 1)

            # If we have alreadily found and answer, we will stop searching further
            if ans:
                graph[si][sj] = cur
                return

        # We visited current and now we might want to check it again for some other moves that we used before it, so we will pop it for now from the solution and mark it as unvisited
        moves.pop()
        vis[si][sj] = False

    
    # If answer exists,it could be found from any cell, so we can assume (1, 1) as the starting point for the search
    dfs(0, 0)

    if not ans:
        print("Solution is not exist")
        
    for i in graph:
        print(i)


n = int(input("Enter the size of board : "))
ans=False
KnightsRoute(n)

print("Thank You")

'''IMPORTANT: The time complexity of this code is very high if we increase the size of input then it take much time to show output 
,check the code up to input 7 for earlier output'''

                                           #THANKS FOR RUN THE CODE```


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM