矩阵中的路径

矩阵中的路径

http://www.nowcoder.com/questionTerminal/c61c6999eecb4b8f88a98f66b273a3cc

非递归深度搜索

    bool hasPath(char* matrix, int rows, int cols, char* str)
    {  
        stack<pair<pair<int, int>, int> > s;
        int next[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};  //右下左上
        int tx, ty, n, m;
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < cols; j++)
            {
                vector<vector<int> > visited(rows,vector<int>(cols, 0));
                if(matrix[i * cols + j] == str[0])
                {
                    pair<int, int> p(i, j);
                    pair<pair<int, int >, int> q(p, 0);
                    s.push(q);
                    while(!s.empty())
                    {   
                        n = s.top().first.first;
                        m = s.top().first.second;
                        if(s.top().second == (strlen(str) - 1))
                            return true;
                        visited[n][m] = 1;
                        int valid = s.top().second;
                        s.pop();
                        for(int k = 0; k < 4; k++)
                        {
                            tx = n + next[k][0];
                            ty = m + next[k][1];
                            if(tx >= 0 && tx < rows && ty >= 0 && ty < cols && 
                            visited[tx][ty] != 1 &&
                            matrix[tx * cols + ty] == str[valid + 1])
                            {
                                pair<int, int> p(tx, ty);
                                pair<pair<int, int >, int> q(p, valid + 1);
                                s.push(q);
                            }
                        }
                        if(!s.empty() && s.top().second == (strlen(str) - 1))
                            return true;
                    }
                }
            }
        return false;
    }
全部评论

相关推荐

故事和酒66:小米现在校招很多都是在高校搞小米训练营,然后直接挑人,大四就去实习,所以实际上校招总名额是变少了的。同学211本无经验经过两周培训直接签了
秋招,不懂就问
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务