stack栈的运用
我是一个编程的新手,然后学校布置一个作业,是用stack栈和Queues队列分别实现填充算法,就是把一个白板,从一个个点往外一个一个像素的填充黑色,以至于全部为黑色。但是作业是让我们用栈和队列来实现算法,不能用递归。求大佬们帮助下面是老师已经写好的组。
class Screen():
"""defines a screen of x times y pixels initially all coloured white"""
def __init__(self, x, y):
self.x = x
self.y = y
self.colour = []
for i in range(x):
self.colour += [["white"]*y]
def __contains__(self, coord):
(p, q) = coord
if 0 <= p and p < self.x and 0 <= q and q < self.y:
return True
else:
return False
def check_pixel(self, p, q):
return self.colour
def fill(self, p, q):
self.colour = "black"
def check_filled(self):
for i in range(self.x):
for j in range(self.y):
if self.colour != "black":
return False
return True
class Node:
def __init__(self, data, before=None, after=None):
self.data = data
self.before = before
self.after = after
class Stack:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def pop(self):
output = self.head.data
self.head = self.head.before
return output
def push(self, data):
self.head = Node(data, self.head)
def top(self):
return self.head.data
class Queue:
def __init__(self):
self.head = None
self.rear = None
def isEmpty(self):
return self.head == None
def dequeue(self):
output = self.head.data
self.head = self.head.after
if self.head == None:
self.rear = None
return output
def enqueue(self, data):
if self.rear == None:
self.head = Node(data)
self.rear = self.head
else:
self.rear.after = Node(data, self.rear)
self.rear = self.rear.after
def front(self):
return self.head.data
def floodfill_recursive(screen, x, y):
"""apply floodfill to screen starting at pixel at coordinate (x,y)"""
#BASE CASE
if ((x, y) in screen) == False: #check if pixel is on screen
return
if screen.check_pixel(x, y) != "white": #check if pixel is currently white
return
#RECURSIVE CASE
screen.fill(x, y) #colour pixel with black
floodfill_recursive(screen, x+1, y) #make recursive calls to all neighbouring pixels
floodfill_recursive(screen, x-1, y)
floodfill_recursive(screen, x, y+1)
floodfill_recursive(screen, x, y-1)
然后这个是老师已经搭建好的函数
我想的是把这个screen屏幕当做一个二维数值然后再用栈一列一列的处理,但是我不知道如何把screen和栈还有二维数值联系起来,因为我用print打印这个栈显示的是一个内存的位置。以至于我没办法去查看里面的元素。
求大佬指导一下如何实现,或者告诉我的方向,谢谢啦
请用代码格式发帖
页:
[1]