我有一个5*6的矩阵,所有的值都是英文字母。我必须在矩阵中从左到右、从右到左、从上到下、从上到对角线找到特定的单词。其实这是一个字谜。
我能找到“左右”、“右左”、“上下”和“下上”这些词。当涉及到对角线查找单词时,事情会变得更加混乱。我提供了从左到右和从右到左搜索的示例代码。
#the word I am looking for
word_list = ["CRAM", "ROTLQ", "TDML", "COOI"]
# create the matrix array or puzzle
letter_array = np.matrix([['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']])
#itenarate through word list
for word in word_list:
#flatten the array, convert it to list,
#finally join everythig to make a long string
left_right = ''.join(letter_array.flatten().tolist()[0])
# flip the string to search from right to left
right_left = left_right[::-1]
# if the word is there, it gives the index otherwise it gives -1
if left_right.find(word)>-1:
row, col = divmod(left_right.find(word), 6)
print ("The word is in left to right combination, row and column = ", row, col)
# look from right to left
elif right_left.find(word)>-1:
row, col = divmod(right_left.find(word), 6)
print ("The word is in right to left combination, row and column = ", row, col)
else:
print ("The word is in up down or diagonally located")
Results
The word is in left to right combination, row and column = 0 0
The word is in left to right combination, row and column = 1 0
The word is in right to left combination, row and column = 0 0
The word is in up down or diagonally located
然而,通过对矩阵进行转置,也可以完成上下和上下的搜索。但是,我不知道如何对角搜索。有什么方法可以对角搜索吗?或者,还有其他简单的解决方案可以解决整个问题吗?