Если ваша матрица всегда будет такой маленькой, я бы предложил вообще не использовать матрицу, а обрабатывать письма через списки косвенных адресов.
# setup indirection lists for each axis
# -------------------------------------
# (only need to do this once)
#
# 00 01 02 03 04 05 <-- list positions corresponding
# 06 07 08 09 10 11 to letter coordinates
# 12 13 14 15 16 17
# 18 19 20 21 22 23
# 24 25 26 27 28 29
horizontal = [ [0,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] ]
vertical = [ [0,6,12,18,24], [1,7,13,19,25], [2,8,14,20,26], [3,9,15,21,27], [4,10,16,22,28], [5,11,17,23,29] ]
diagonal = [ [6,1], [12,7,2], [18,13,8,3], [24,19,14,9,4], [25,20,15,10,5], [26,21,16,11], [27,22,17], [28,23],
[4,11], [3,10,17], [2,9,16,23], [1,8,15,22,29], [0,7,14,21,28], [6,13,20,27], [12,29,26], [18,25] ]
horizontal = horizontal + [ list(reversed(positions)) for positions in horizontal ]
vertical = vertical + [ list(reversed(positions)) for positions in vertical ]
diagonal = diagonal + [ list(reversed(positions)) for positions in diagonal ]
# Generate the letter matrix as a simple list:
letter_array = ['C','R','A','M','B','A',
'R','O','T','L','Q','C',
'E','O','O','A','U','A',
'I','T','E','I','A','L',
'I','A','L','M','D','T' ]
word_list = ["CRAM", "ROTLQ", "TDML", "COOI"]
# transpose letter matrix into list of strings for each axis segment
horizontalStrings = [ "".join(map(lambda i:letter_array[i],positions)) for positions in horizontal]
verticalStrings = [ "".join(map(lambda i:letter_array[i],positions)) for positions in vertical]
diagonalStrings = [ "".join(map(lambda i:letter_array[i],positions)) for positions in diagonal]
# check for words ...
for word in word_list:
if any(filter(lambda string:word in string, horizontalStrings)):
print(word, " found horizontally")
elif any(filter(lambda string:word in string, verticalStrings)):
print(word, " found vertically")
elif any(filter(lambda string:word in string, diagonalStrings)):
print(word, " found diagonally")
else:
print(word, " not found")
[РЕДАКТИРОВАТЬ] Для обобщения подхода для любого размера сеткиВы можете инициализировать списки косвенного обращения следующим образом:
rowCount = 5
colCount = 6
goRight = [ [ row*colCount+col for col in range(colCount) ] for row in range(rowCount) ]
goLeft = [ list(reversed(positions)) for positions in goRight ]
goDown = [ [ row*colCount+col for row in range(rowCount) ] for col in range(colCount) ]
goUp = [ list(reversed(positions)) for positions in goDown ]
goDownRight = [ [ row*colCount+row+col for row in range(min(rowCount,colCount-col))] for col in range(colCount-1) ] \
+ [ [ (row+col)*colCount+col for col in range(min(rowCount-row,colCount))] for row in range(1,rowCount-1) ]
goUpLeft = [ list(reversed(positions)) for positions in goDownRight ]
goDownLeft = [ [ row*colCount-row+col for row in range(min(rowCount,col+1))] for col in range(1,colCount) ] \
+ [ [ (row+1+col)*colCount-1-col for col in range(min(rowCount-row,colCount))] for row in range(1,rowCount-1) ]
goUpRight = [ list(reversed(positions)) for positions in goDownLeft ]
segments = [ ("horizontally going right", segment) for segment in goRight ] \
+ [ ("horizontally going left", segment) for segment in goLeft ] \
+ [ ("vertically going down", segment) for segment in goDown ] \
+ [ ("vertically going up", segment) for segment in goUp ] \
+ [ ("diagonally going down-right", segment) for segment in goDownRight ] \
+ [ ("diagonally going up-left", segment) for segment in goUpLeft ] \
+ [ ("diagonally going down-left", segment) for segment in goDownLeft ] \
+ [ ("diagonally going up-right", segment) for segment in goUpRight ]
Используя список косвенного обращения сегментов, все направления управляются в общем порядке, позволяя логике поиска сосредоточиться на словах, а не на вычислениях координат:
# Generate the letter matrix as a simple list:
letter_array = ['C','R','A','M','B','A',
'R','O','T','L','Q','C',
'E','O','O','A','U','A',
'I','T','E','I','A','L',
'I','A','L','M','D','T' ]
word_list = ["CRAM", "ROTLQ", "TDML", "COOI", "ROOT", "BLOT", "ALM", "ACA"]
# transpose letter matrix into list of strings for each axis segment
segmentStrings = [ (direction,positions,"".join(map(lambda i:letter_array[i],positions))) for direction,positions in segments ]
# check for words ...
for word in word_list:
for direction,positions,segmentString in segmentStrings:
startPos = segmentString.find(word) # see note below
if startPos < 0: continue
wordPositions = positions[startPos:][:len(word)]
gridPositions = [ (position // colCount, position % colCount) for position in wordPositions ]
print(word,"found\t starting at",wordPositions[0],direction,gridPositions)
break # don't break here if you want to find all matches
Использование (position // colCount, position% colCount) позволяет получить координаты 2D-сетки.Это приведет к следующему результату:
CRAM found starting at 0 horizontally going right [(0, 0), (0, 1), (0, 2), (0, 3)]
ROTLQ found starting at 6 horizontally going right [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]
TDML found starting at 29 horizontally going left [(4, 5), (4, 4), (4, 3), (4, 2)]
COOI found starting at 0 diagonally going down-right [(0, 0), (1, 1), (2, 2), (3, 3)]
ROOT found starting at 1 vertically going down [(0, 1), (1, 1), (2, 1), (3, 1)]
BLOT found starting at 4 diagonally going down-left [(0, 4), (1, 3), (2, 2), (3, 1)]
ALM found starting at 25 horizontally going right [(4, 1), (4, 2), (4, 3)]
ACA found starting at 5 vertically going down [(0, 5), (1, 5), (2, 5)]
Примечание. Если вы хотите найти все совпадения для каждого слова (например, чтобы решить загадку со скрытым словом), вам понадобится дополнительная логика в цикле сегментной строкинайти все экземпляры слова в каждом сегменте (в отличие от 1-го, который даст этот пример).Вы можете также захотеть иметь специальный случай для палиндромов (например, ACA), который выйдет дважды (один раз в каждом противоположном направлении)