cols

题目描述

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

代码

int dir[4][2] = {
        {1, 0},
        {-1, 0},
        {0, 1},
        {0, -1}
};
class Solution {
    int rows, cols, size;
    char* mat;
    char* str;
    vector<int> visited;
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if (str[0] != '') {
            this->size = rows * cols;
            vector<int> visited(this->size, 0);
            this->visited = visited;
            this->mat = matrix;
            this->rows = rows;
            this->cols = cols;
            this->str = str;

            for (int i = 0; i < this->size; ++i) {
                if (matrix[i] == str[0]) {
                    if (dfs(i, 1)) {
                        return true;
                    }
                    this->visited.assign(this->size, 0);
                }
            }
        }
        return false;
    }

    bool dfs(int x, int p) {
        if (str[p] == '') {
            return true;
        }
        visited[x] = 1;

        int xi;
        for (int i = 0; i < 4; ++i) {
            xi = check(x, i);
            if (xi > -1 && !visited[xi] && str[p] == mat[xi]) {
                if (dfs(xi, p + 1)) {
                    return true;
                }
            }
        }
        return false;
    }

    int check(int x, int i) {
        int xi = x / this->cols + dir[i][0], yi = x % this->cols + dir[i][1];
        return (xi > -1 && xi < this->rows && yi > -1 && yi < this->cols) ? (xi * this->cols + yi) : -1;
    }
};
原文地址:https://www.cnblogs.com/jecyhw/p/6654982.html