检查单词是否存在于网格中或不存在于Python中
假设我们有一个网格或单词矩阵。我们必须检查给定单词是否存在于网格中。可以通过四种方式找到该单词,即水平向左和向右以及垂直向上和向下。如果可以找到单词,则返回True,否则返回False。
所以,如果输入像
input_str=“python”,则输出为True。
示例
让我们看下面的实现以更好地理解-
def find_grid(matrix, input_str, row_pos, col_pos, row_count, col_count, degree) : if (degree == len(input_str)) : return True if (row_pos < 0 or col_pos < 0 or row_pos >= row_count or col_pos >= col_count) : return Fals if (matrix[row_pos][col_pos] == input_str[degree]) : temp = matrix[row_pos][col_pos] matrix[row_pos].replace(matrix[row_pos][col_pos], "#") result = (find_grid(matrix, input_str, row_pos - 1, col_pos, row_count, col_count, degree + 1) |find_grid(matrix, input_str, row_pos + 1, col_pos, row_count, col_count, degree + 1) |find_grid(matrix, input_str, row_pos, col_pos - 1, row_count, col_count, degree + 1) |find_grid(matrix, input_str, row_pos, col_pos + 1, row_count, col_count, degree + 1)) matrix[row_pos].replace(matrix[row_pos][col_pos], temp) return result else : return False def solve(matrix, input_str, row_count, col_count) : if (len(input_str) > row_count * col_count) : return False for row in range(row_count) : for col in range(col_count) : if (matrix[row][col] == input_str[0]) : if (find_grid(matrix, input_str, row, col, row_count, col_count, 0)) : return True return False word_grid = ["pghsf", "ykdgh", "tkghi", "hnsjs", "ojfgh", "nrtyu"] print(solve(word_grid, "python", 6, 5))
输入
["pghsf", "ykdgh", "tkghi", "hnsjs", "ojfgh", "nrtyu"],"python"输出结果
True