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];
    
    };
  • 相关阅读:
    bzoj 4012: [HNOI2015]开店
    POJ 1054 The Troublesome Frog
    POJ 3171 Cleaning Shifts
    POJ 3411 Paid Roads
    POJ 3045 Cow Acrobats
    POJ 1742 Coins
    POJ 3181 Dollar Dayz
    POJ 3040 Allowance
    POJ 3666 Making the Grade
    洛谷 P3657 [USACO17FEB]Why Did the Cow Cross the Road II P
  • 原文地址:https://www.cnblogs.com/langyao/p/10631979.html
Copyright © 2011-2022 走看看