zoukankan      html  css  js  c++  java
  • 题目66:矩阵中的路径

    又是一道回溯法的问题。目前关于回溯法,只是处于能看懂代码的阶段。给你一道新题,估计还是很难答得出来,不过没关系。先把这几道题弄熟了再说。

    bool HasPathCore(char* matrix, int rows, int columns, int row, int col, char* str, int &length, bool* visited)
    {
        if (str[length] == '')
            return true;
    
        bool HasPath = false;
    
        if (row < rows&&row >= 0 && col >= 0 && col < columns&&matrix[row*columns + col] == str[length] && visited[row*columns + col] == false)
        {
            ++length;
            visited[row*columns + col] = true;
            HasPath = HasPathCore(matrix, rows, columns, row, col - 1, str, length, visited) || HasPathCore(matrix, rows, columns, row, col + 1, str, length, visited) || HasPathCore(matrix, rows, columns, row - 1, col, str, length, visited) || HasPathCore(matrix, rows, columns, row + 1, col, str, length, visited);
    
            if (!HasPath)
            {
                --length;
                visited[row*columns + col] = false;
            }
        }
        return HasPath;
    }
    //确定图中是否有可以使用的路径
    bool HasPath(char* matrix, int rows, int columns, char* str)
    {
        if (matrix == NULL || rows <= 0 || columns <= 0 || str == NULL)
            return false;
    
        bool *visited = new bool[rows*columns];
    
        memset(visited, 0, rows*columns);
    
        int PathLength = 0;
        for (int col = 0; col < columns; col++)
        {
            for (int row < 0; row < rows; ++row)
            {
                if (HasPathCore(matrix, rows, columns, row, col, str, PathLength, visited))
                    return true;
            }
        }
        delete[] visited;
        return false;
    }
  • 相关阅读:
    js兼容性——获取当前浏览器窗口的宽高
    pip 换源
    5 二分查找 算法
    顺序查找 冒泡 快排 等
    4 顺序表和链表
    python垃圾回收机制
    3 栈 队列 双头队列
    2 数据结构的性能分析 timeit
    1 时间复杂度
    线程池 爬取一本小说
  • 原文地址:https://www.cnblogs.com/chengxuyuanxiaowang/p/4304373.html
Copyright © 2011-2022 走看看