zoukankan      html  css  js  c++  java
  • [leetCode]剑指 Offer 12. 矩阵中的路径

    在这里插入图片描述

    回溯法

    回溯法适合由多个步骤组成的问题,并且每个步骤有多个选项。在某一步选择一个选项如果符合约束条件则进入下一步,如果不符合约束条件则回到上一步,就这样重复选择直至达到最终状态。

    class Solution {
        public boolean exist(char[][] board, String word) {
            if(board == null || word == null || board.length == 0){
                return false;
            }
            int rows = board.length;
            int cols = board[0].length;
            //创建一个辅助矩阵,用于标识路径是否已经进入过格子
            boolean[][] visited = new boolean[rows][cols];
            int pathLengh = 0;
            //对矩阵每个元素进行查询
            for(int row = 0; row < rows; row++){
                for(int col = 0; col < cols; col++){
                    if(hasPathCore(board,visited,row,col,pathLengh,word,rows,cols)){
                        return true;
                    }
                }
            }
            return false;
        }
    
        private boolean hasPathCore(char[][] board,boolean[][] visited,
                                int row, int col, 
                                int pathLengh, String word, 
                                int rows, int cols) {
            if(pathLengh == word.length())
                return true;
            boolean hasPath = false;
            if(row >= 0 && row < rows && col >= 0 && col< cols 
            && board[row][col] == word.charAt(pathLengh) && !visited[row][col]){
                ++pathLengh;
                visited[row][col] = true;
                hasPath = hasPathCore(board,visited,row-1,col,pathLengh,word,rows,cols)||
                            hasPathCore(board,visited,row+1,col,pathLengh,word,rows,cols)||
                            hasPathCore(board,visited,row,col-1,pathLengh,word,rows,cols)||
                            hasPathCore(board,visited,row,col+1,pathLengh,word,rows,cols);
                if(!hasPath){
                    --pathLengh;
                    visited[row][col] = false;
                }
            }
            return hasPath;
        }
    }
    
  • 相关阅读:
    VS中添加搜索路径和链接库的方法
    hive多分隔符支持
    shell 遍历目录下的所有文件
    使用ansible控制Hadoop服务的启动和停止【转】
    Shell中的括号有其特殊的用法
    shell中括号[]的特殊用法 linux if多条件判断
    Linux中rz和sz命令用法详解
    vim 去掉自动注释和自动回车
    ping判断局域网ip使用情况
    shell判断有效日期
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859980.html
Copyright © 2011-2022 走看看