简体   繁体   English

Python算法:算法的复杂性是什么?如何优化它?

[英]Python algorithm: What is the complexity of my algorithm and how can I optimize it?

I'm trying to accomplish a task in which you are given n (the size of a square chessboard, queens (the squares they occupy), and queries(a list of coordinates). I am to return a list of Boolean values saying whether or not each query is attackable by any of the queens. I know my algorithm works but I also know that it isn't efficient "enough". Through research, I'm guessing that the complexity is O(queens queries)? So that's my first questions, is it O(queens queries), if not why? Second, does anyone have an idea how I can optimize it possibly even down to O(queens + queries)? I apologize if this is a rudimentary question, but I am mainly self-taught and don't have anyone I can ask this. Thanks in advance! 我正在尝试完成一项任务,给您n个(棋chess的大小,皇后(他们占据的正方形)和查询(一个坐标列表)。我要返回一个布尔值列表,说明是否是不是每个查询都可以被任何皇后攻击。我知道我的算法是可行的,但我也知道它“不够”有效。通过研究,我猜它的复杂度是O(女王查询)?我的第一个问题是O(问号查询),如果不是为什么呢?其次,有没有人知道我如何优化它,甚至可以降低到O(问号+查询)?如果这是一个基本问题,我深表歉意,但是我我主要是自学成才,没有人可以问这个,谢谢。

def squaresUnderQueenAttack(n, queens, queries):
    output = []
    for i in queries:
        attackable = False
        for j in queens:
            if attackable != True and (i[0]==j[0] or i[1]==j[1] or abs(i[0]-j[0])==abs(i[1]-j[1])):
                attackable = True
                break
        output.append(attackable)
    return output

Your current code is O(queens * queries) . 您当前的代码是O(queens * query) You can improve it to O(queens + queries) . 您可以将其改进为O(queens + query)

Make three arrays, each with 8 elements. 制作三个数组,每个数组包含8个元素。 Call them row , col , diagleft , and diagright . 称它们为rowcoldiagleftdiagright

Look at each queen, if it's in row 0, set that spot in row to true. 看看每个女王,如果它是在第零行, 现货设置为true。 If it's in col 3, set that spot to col in true. 如果是在第3栏设置点在真实的山坳 Label the diagonals 0-7 and make appropriate marks in them as well. 标记对角线0-7,并在其中标记适当的位置。

Now the arrays indicate all of the rows, columns, and diagonals that have queens. 现在,数组将指示所有具有皇后号的行,列和对角线。

Now, look at each query and check to see if any of the array entries corresponding to its location are marked true. 现在,查看每个查询并检查是否对应于其位置的任何数组条目都标记为true。 If so, then a queen threatens it. 如果是这样,则女王会威胁它。

Note that in big-O notation, we're interested in which factor "dominates" the run-time, so the above solution is probably more appropriately thought of as operating in O(max(queens,queries)) time. 请注意,在big-O表示法中,我们关注哪个因素“主导”了运行时间,因此,上述解决方案可能更适合视为在O(max(queens,queries))时间内运行。 That is, if you have many queries, the queens calculation takes only a little time. 也就是说,如果您有很多查询,则皇后区计算只需要一点时间。 Similarly, if you have many queens and few queries, that operation will take most of your time. 同样,如果您有很多皇后和很少的查询,那么该操作将花费您大部分时间。

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

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