zoukankan      html  css  js  c++  java
  • 剑指offer--49.矩阵中的路径

    时间限制:1秒 空间限制:32768K 热度指数:156998

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
    class Solution {
        public:
            bool hasPath(char* matrix, int rows, int cols, char* str) {
                string str_cp(str);
                if(str_cp == "") return true;
                row = rows;
                col = cols;
                memset(alpha, 0, sizeof(alpha));
                memset(ma, 0, sizeof(ma));
                for(int i=0,k=0; i<rows; i++) {//保存地图
                    for(int j=0; j<cols; j++)  {
                        alpha[i][j] = matrix[k++];
                    }
                }
                for(int i=0; i<rows; i++) {//找开头
                    for(int j=0; j<cols; j++)  {
                        if( alpha[i][j] == str_cp[0]) {
                            ma[i][j] = 1;
                            if(str_cp.size() > 1){
                                if(dfs(i, j, str_cp,1) == true) return true;
                            }
                            else return true;
                            ma[i][j] = 0;
                        }
                    }
                }
                return false;
            }
            bool dfs(int r, int c, string str, int pos) {
                for(int i=0; i<4; i++) {
                    int newr = dir[i][0] + r;
                    int newc = dir[i][1] + c;
                    if(ma[newr][newc] || alpha[newr][newc]!=str[pos] ||newr<0 || newc<0|| newr>=row|| newc>=col)continue;
                    ma[newr][newc] = 1;
                    if(str.size() == pos+1) return true;
                    if(dfs(newr, newc, str, pos+1) == true) return true;
                    ma[newr][newc] = 0;
                }
                return false;
            }
        private:
            int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
            int row, col;
            char alpha[100][100];
            int ma[100][100];
    
    };
  • 相关阅读:
    linux中断处理浅析
    linux页面回收浅析
    linux线程同步浅析
    剖析一个由sendfile引发的linux内核BUG
    比memcpy更快的内存拷贝
    linux内核SMP负载均衡浅析
    sscanf,snprintf
    mysql中实现longblob数据流式读写
    sscanf
    substr复制字符串的一部分
  • 原文地址:https://www.cnblogs.com/slothrbk/p/10631979.html
Copyright © 2011-2022 走看看