表示非方形棋盘游戏的数据结构可以使用二维数组或链表。
一、使用二维数组
class Chessboard:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.board = [[' ' for _ in range(cols)] for _ in range(rows)]
def print_board(self):
for row in self.board:
print('|'.join(row))
def update_cell(self, row, col, value):
self.board[row][col] = value
# 示例用法
chessboard = Chessboard(5, 7)
chessboard.update_cell(2, 3, 'X')
chessboard.update_cell(4, 6, 'O')
chessboard.print_board()
二、使用链表
class Cell:
def __init__(self, row, col, value):
self.row = row
self.col = col
self.value = value
self.next = None
class Chessboard:
def __init__(self):
self.head = None
def print_board(self):
current = self.head
while current:
print(f"({current.row}, {current.col}): {current.value}")
current = current.next
def update_cell(self, row, col, value):
if not self.head:
self.head = Cell(row, col, value)
else:
current = self.head
while current.next:
current = current.next
current.next = Cell(row, col, value)
# 示例用法
chessboard = Chessboard()
chessboard.update_cell(2, 3, 'X')
chessboard.update_cell(4, 6, 'O')
chessboard.print_board()
以上是两种表示非方形棋盘游戏的数据结构的解决方法,你可以根据自己的需求选择其中一种来使用。
下一篇:标识符 "thread" 未定义