• 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。


    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

    拙见:

    回溯的思想。

    # -*- coding:utf-8 -*-
    class Solution:
        def hasPath(self, matrix, rows, cols, path):
            # write code here
            visited = [True for i in range(rows*cols)]
            k = 0
            length = len(path)
            for i in range(rows*cols):
                if self.hasPathNext(matrix, visited, path, rows, cols, i/cols, i%cols, k, length):
                    return True
            return False
        def hasPathNext(self, matrix, visited, path, rows, cols, i, j, k, length):
            if k > length-1:
                return True
            if i>=0 and i<rows and j>=0 and j<cols and visited[i*cols+j] and matrix[i*cols+j]==path[k]:
                k += 1
                visited[i*cols+j] = False
                if self.hasPathNext(matrix, visited, path, rows, cols, i, j-1, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i+1, j, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i, j+1, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i-1, j, k, length):
                    return True
                else:
                    k -= 1
                    visited[i*cols+j] = True
                    return False
            else:
                return False
    

    牛油高见:

    # -*- coding:utf-8 -*-
    class Solution:
        def hasPath(self, matrix, rows, cols, path):
            # write code here
            for i in range(rows):
                for j in range(cols):
                    if matrix[i*cols+j] == path[0]:
                        if self.find(list(matrix),rows,cols,path[1:],i,j):
                            return True
            return False
        def find(self,matrix,rows,cols,path,i,j):
            if not path:
                return True
            matrix[i*cols+j]='0'
            if j+1<cols and matrix[i*cols+j+1]==path[0]:
                return self.find(matrix,rows,cols,path[1:],i,j+1)
            elif j-1>=0 and matrix[i*cols+j-1]==path[0]:
                return self.find(matrix,rows,cols,path[1:],i,j-1)
            elif i+1<rows and matrix[(i+1)*cols+j]==path[0]:
                return self.find(matrix,rows,cols,path[1:],i+1,j)
            elif i-1>=0 and matrix[(i-1)*cols+j]==path[0]:
                return self.find(matrix,rows,cols,path[1:],i-1,j)
            else:
                return False
    
  • 相关阅读:
    取时间
    DEV控件属性
    Dev之barManager控件属性
    linq查询Contains
    绑定
    运算符转换方法组和int类型的操作数
    学习计划实践
    学习计划2
    foreacht学习
    Spring5源码分析(二) IOC 容器的初始化(五)
  • 原文地址:https://www.cnblogs.com/ChangAn223/p/10828238.html
Copyright © 2020-2023  润新知