zoukankan      html  css  js  c++  java
  • 12. 矩阵中的路径

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

    [["a","b","c","e"],
    ["s","f","c","s"],
    ["a","d","e","e"]]

    但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

    示例 1:

    输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
    输出:true
    

    示例 2:

    输入:board = [["a","b"],["c","d"]], word = "abcd"
    输出:false
    

    提示:

    • 1 <= board.length <= 200
    • 1 <= board[i].length <= 200
    class Solution {
        public boolean exist(char[][] board, String word) {
            if(word == null || word.length() == 0) return true;
            // List<Character> list = new ArrayList<>();
            boolean[][] visited = new boolean[board.length][board[0].length];
            for(int i = 0;i < board.length;i++){
                for(int j = 0;j < board[0].length;j++){
                    if(dfs(board,i,j,0,word,visited))
                        return true;
                }
            }
            return false;
            
        }
        
        private boolean dfs(char[][] board,int i, int j,int index,String word,boolean[][] visited){
            if(index == word.length()) return true;
            if(i >= board.length || i < 0 || j < 0 || j >= board[0].length || visited[i][j] || 
                       index >= word.length() || board[i][j] != word.charAt(index)){
                return false;
            }
            visited[i][j] = true;
            // list.add(board[i][j]);
            if(dfs(board,i + 1,j,index + 1,word,visited) || dfs(board,i,j + 1,index + 1,word,visited) ||
               dfs(board,i - 1,j,index + 1,word,visited) ||dfs(board,i,j - 1,index + 1,word,visited) ){
                return true;
            }
            // list.remove(list.size() - 1);
            visited[i][j] = false;
            return false;
        }
    }
    一回生,二回熟
  • 相关阅读:
    【Oracle 故障处理一则】 ORA-600
    【转载】关于物化视图
    【转载】OTLP和OLAP的区别
    【转载】Linux追加虚拟内存Swap
    【转载】Keepalived 的使用
    【识记】修复oracle的坏块
    K-means算法[聚类算法]
    决策树ID3算法[分类算法]
    6)图[1]之邻接矩阵存储[深度遍历和广度遍历]
    2)杨辉三角[2]递归实现
  • 原文地址:https://www.cnblogs.com/zzytxl/p/12637131.html
Copyright © 2011-2022 走看看