题解

矩阵中的路径

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

题解

 public int[][] visit;
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
      visit = new int[rows][cols];
      char[][] array = new char[rows][cols];
      for (int i = 0; i < rows ; i++) {
          for(int j = 0; j < cols; j++) {
              array[i][j] = matrix[i*cols + j];
          }
      }
        for (int i = 0; i < rows ; i++) {
            for(int j = 0; j < cols; j++) {
               if(find(array,rows,cols,str,i,j,0)){
                   return  true;
               }
            }
        }
      return false;
    }
    public boolean find(char[][] array, int rows, int cols, char[] str, int rpos,int cpos, int spos) {

        if(spos >= str.length) {
            return  true;
        }
       if(rpos < 0 || cpos < 0 || rpos >= rows || cpos >= cols || array[rpos][cpos] != str[spos] || visit[rpos][cpos] == 1) {

          return false;
       }
       visit[rpos][cpos] = 1;
       boolean isSunc =  find( array,   rows,  cols, str,  rpos+1, cpos, spos+1)
               || find( array,   rows,  cols, str,  rpos , cpos+1, spos+1)
               || find( array,   rows,  cols, str,  rpos-1, cpos, spos+1)
               || find( array,   rows,  cols, str,  rpos , cpos-1, spos+1);
       visit[rpos][cpos] = 0;
       return isSunc;
    }
全部评论
大佬,我想问一下array[i][j] = matrix[i*cols + j]是什么意思,原谅我渣渣看不懂
点赞 回复
分享
发布于 2020-07-23 15:01
为什么把标志数组置1又置0啊 visit[rpos][cpos] = 1; boolean isSunc = find( array, rows, cols, str, rpos+1, cpos, spos+1) || find( array, rows, cols, str, rpos , cpos+1, spos+1) || find( array, rows, cols, str, rpos-1, cpos, spos+1) || find( array, rows, cols, str, rpos , cpos-1, spos+1); visit[rpos][cpos] = 0;
点赞 回复
分享
发布于 2020-08-26 11:10
滴滴
校招火热招聘中
官网直投

相关推荐

22 收藏 评论
分享
牛客网
牛客企业服务