矩阵中的路径

矩阵中的路径

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

这道题坑太多了,思路虽然简单,但是想考虑得完整太难了。

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if (matrix == nullptr || str == nullptr || rows < 1 || cols < 1)
            return false;
        bool* markmatrix = new bool[rows * cols]();
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                memset(markmatrix, 0, rows * cols);
                if (hasPathCore(matrix, rows, cols, str, i, j, markmatrix))
                    return true;
            }
        }
        return false;
    }
    bool hasPathCore(char* matrix, int rows, int cols, char* str, int x, int y, bool* markmatrix)
    {
        if (*str == 0)
            return true;
        if (*str == matrix[x * cols + y])
        {
            if (*(str + 1) == 0)
                return true;
            markmatrix[x * cols + y] = true;
            cout << x << "   " << y << endl;
            bool a = false, b = false, c = false, d = false;
            if (x + 1 < rows && markmatrix[(x + 1) * cols + y] == false)
                a = hasPathCore(matrix, rows, cols, str+1, x + 1, y, markmatrix);
            if (x - 1 >= 0 && markmatrix[(x - 1) * cols + y] == false)
                b = hasPathCore(matrix, rows, cols, str+1, x - 1, y, markmatrix);
            if (y + 1 < cols && markmatrix[x * cols + y + 1] == false)
                c = hasPathCore(matrix, rows, cols, str+1, x, y + 1, markmatrix);
            if (y - 1 >= 0 && markmatrix[x * cols + y - 1] == false)
                d = hasPathCore(matrix, rows, cols, str+1, x, y - 1, markmatrix);
            markmatrix[x * cols + y] = false;
            return a || b || c || d;
        }
        else
        {
            return false;
        }
    }
};

遇到的坑

  • x、y与rows、cols的关系傻傻分不清。
  • 代码复制非常容易出问题
  • 不应该最后用循环到最后*str==0来判断是否有序列,因为如果序列个数和矩阵元个数相等,就没有多余的位置循环换都\0.
  • 写法还可以再优化,把所有条件判断都放到前面判断,四个递归调用只管传参数,不用管是否有效。
全部评论

相关推荐

大方的大熊猫准备进厂:1.教育背景:你希望从事什么专业的工作你的主修课就是什么;成绩优秀是你应该做的,没什么可描述的,成绩不优秀也许人家在大学忙着创业呢?(成绩优秀不一定是好事,只能说明多元化的大学你上成了高中,没有真正上明白大学,反而体现了你死板,不爱社交,没有别的突出能力) 2.实践经历:你想表达的意思没有说清楚。你是说你会个性化服务,还是你有实习经历。如果没有带来,经济收益,表彰,更好的发展前景,那你还不如说说提升了自己哪些技能。你说有人给你送锦旗我都能明白你优秀,但是你说你会xxxx,你说这话谁信,证据呢。 3.入伍经历:你描述的就是你的工作职责或者你应该做的,并没有体现出来你把这个事情做好了,而且入伍经历并不能证明你能干好你要应聘的工作,不如只写经历其余所有内容都不写。 4.荣誉技能:重点突出一下,但不要过多描述,这些荣誉的含金量懂得都懂。 重点:你要应聘什么工作(具体岗位,实习生不具体),你的期望薪资
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-29 20:12
点赞 评论 收藏
分享
评论
7
收藏
分享

创作者周榜

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