剑指offer65:矩阵中的路径

题目描述:

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

class Solution {
private:
    bool dfs(char* matrix, int rows, int cols, char* str, int pos,
            vector<pair<int, int>>& visited) {
        if (pos == strlen(str)) {
            return true;
        }

        pair<int, int> last = visited.back();
        vector<pair<int, int>> four = { { last.first - 1, last.second },
                                        {last.first + 1, last.second },
                                        { last.first, last.second - 1 },
                                        { last.first, last.second + 1 } };
        for(pair<int,int> p : four){
            if(p.first >=0 && p.first <rows && p.second>=0 && p.second <cols && matrix[p.first*cols+p.second] == *(str+pos)){
                if(visited.end() == find(visited.begin(),visited.end(),p)){
                    visited.push_back(p);
                    if(dfs(matrix,rows,cols,str,pos+1,visited)) return true;
                    visited.pop_back();
                }
            }
        }
        return false;

    }
public:
    bool hasPath(char* matrix, int rows, int cols, char* str) {
        vector<pair<int, int>> visited;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i*cols+j] == *str) {
                    visited.push_back(pair<int, int> { i, j });
                    if (dfs(matrix, rows, cols, str, 1, visited))
                        return true;
                    visited.clear();
                }
            }
        }
        return false;
    }
};

 

posted @ 2017-04-26 10:05  wxquare  阅读(399)  评论(0编辑  收藏  举报