Sword refers to the path in the offer12 matrix

Title address

https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

Ideas

A complete string, which may start from any character in the matrix so iterate through each element in depth

  • key point:
  • 1、dfs
  • 2. Store the traversed matrix
  • 3. Direction offset matrix

Code


/**
 * @Auther: wwh
 * @Date: 2020-03-24 22:12
 * @Description:  2020年03月24日22:31:13 --2020年03月24日23:28:35
 * 一个完整的字符串,可能从矩阵中任何一个字符开始  所以深度遍历每个元素
 * 关键点:
 * 1、dfs
 * 2、存储遍历过的矩阵
 * 3、方向偏移量矩阵
 */
public class Solution {

    int col = 0;
    int row = 0;
    String word = "";
    char[][] board ;
    private boolean[][] visted;
    //定义方向偏移量,左 下  上  右
    private int[][] direction = {{-1, 0},
            {0, -1},
            {0, 1},
            {1, 0}};

    //2020年03月24日22:39:10
    public boolean exist(char[][] board, String word) {
        if(board==null||board.length==0||word==null||word.length()==0){
            return false;
        }
        row = board.length;
        col = board[0].length;
        this.word = word;
        this.board = board;
        visted = new boolean[row][col];
        for(int i=0;i<row;i++){
            for(int j = 0;j<col;j++){
                if(dfs(i,j,0)){
                    return true;
                }
                //在这里new  就不可以
                //visted = new boolean[row][col];
            }
        }
        return false;
    }
    public boolean dfs(int i,int j,int wordIndex){
        if(wordIndex==word.length()-1){
            return board[i][j] == word.charAt(wordIndex);
        }
        //如果目标字符串的字母和矩阵中某个相同,则深度遍历
        if(board[i][j]==word.charAt(wordIndex)){
            //表示此格子不能再被检索
            visted[i][j] = true;
            //四个方向依次遍历
            for(int k=0;k<4;k++){
                int newX = i + direction[k][0];
                int newY = j + direction[k][1];
                if(inRanage(newX,newY)&&!visted[newX][newY]){
                    if (dfs(newX, newY, wordIndex + 1)) {
                        return true;
                    }
                }
            }

            //执行完此次递归  变为可用   TODO 为什么在外边的循环中每次new状态变量就不可以呢?
            visted[i][j] = false;
        }

        return false;
    }


    private boolean inRanage(int x, int y) {
        return x >= 0 && x < row  && y >= 0 && y < col;
    }

    public static void main(String[] args) {

         char[][] board =
                 {
                         {'C', 'A', 'A'},
                         {'A', 'A', 'A'},
                         {'B', 'C', 'D'}
                 };

         Solution s = new Solution();
        System.out.println(s.exist(board, "AAB"));

    }

}

doubt

Why doesn't TODO change the new state variable every time in the outer loop?

Published 33 original articles · praised 37 · 110,000 views

Guess you like

Origin blog.csdn.net/hagle_wang/article/details/105084539