【剑指Offer 12】矩阵中的路径

/**
 * 剑指 Offer 12. 矩阵中的路径
 * https://leetcode.cn/problems/ju-zhen-zhong-de-lu-jing-lcof/
 * 
 * 思路:深度优先搜索
 * */
public class Solution {
    private char[][] board;
    private String word;
    private int m;
    private int n;
    private boolean[][] marked;

    public boolean exist(char[][] board, String word) {
        this.board = board;
        this.word = word;
        m = board.length;
        n = board[0].length;
        marked = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] != word.charAt(0)) {
                    continue;
                }
                if(dfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(int i, int j, int index) {
        if (index == word.length()) {
            return true;
        }
        if (i < 0 || i >= m || j < 0 || j >= n) {
            return false;
        }
        if (marked[i][j] == true || board[i][j] != word.charAt(index)) {
            return false;
        }
        marked[i][j] = true;
        index++;
        boolean result = dfs(i + 1, j, index)
                || dfs(i - 1, j, index)
                || dfs(i, j + 1, index)
                || dfs(i, j - 1, index);
        marked[i][j] = false;
        return result;
    }
}
posted @ 2022-06-25 21:25  廖子博  阅读(22)  评论(0编辑  收藏  举报