程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode solution (1591): strange printer II (Python)

編輯:Python


subject :​ ​ The original title is link ​​( difficult )

label : Greedy Algorithm

solution

Time complexity

Spatial complexity

Execution time

Ans 1 (Python)

O ( N × M )

O ( N × M )

132ms (100%)

Ans 2 (Python)

Ans 3 (Python)

Solution 1 :

# Check sequence legality

class Order:
class Node:
def __init__(self, i):
self.i = i
self.children = []

def __init__(self, n):
self.n = n
self.node_list = [self.Node(i) for i in range(n)]

def add(self, since, to):
if self._has_child(to, since):
return False
else:
self.node_list[since].children.append(self.node_list[to])
return True

def _has_child(self, i, aim):
waiting_nodes = collections.deque([self.node_list[i]])
while waiting_nodes:
node = waiting_nodes.popleft()
for child in node.children:
if child.i == aim:
return True
waiting_nodes.append(child)
return False


class Solution:
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
# Traverse to check all colors and the top of the color 、 At the bottom 、 Leftmost left 、 The most right ( successively ) The location of
# O(N×M)
color_dict = {}
m = len(targetGrid)
n = len(targetGrid[0])
for i in range(m):
for j in range(n):
color = targetGrid[i][j]
if color not in color_dict:
color_dict[color] = [i, i, j, j]
else:
color_dict[color][0] = min(color_dict[color][0], i)
color_dict[color][1] = max(color_dict[color][1], i)
color_dict[color][2] = min(color_dict[color][2], j)
color_dict[color][3] = max(color_dict[color][3], j)

# Check the printing order of each color one by one ( That is, the number within the range of the color has been printed later than it )
order_list = set()
for color in color_dict:
position = color_dict[color]
for i in range(position[0], position[1] + 1):
for j in range(position[2], position[3] + 1):
if targetGrid[i][j] != color:
order = (color, targetGrid[i][j])
if order not in order_list:
order_list.add(order)

# print(order_list)

# Check if the sequence is possible
order_monitor = Order(61)
for order in order_list:
if not order_monitor.add(order[0], order[1]):
return False

return True
  • 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.




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved