剑指Offer-09-矩阵中的距离

/**
 * 矩阵中的距离:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
 * 首先对所整个矩阵遍历,找到第一个字符,然后向上下左右查找下一个字符,由于每个字符都是相同的判断方法
 * (先判断当前字符是否相等,再向四周查找),因此采用递归函数。由于字符查找过后不能重复进入,
 * 所以还要定义一个与字符矩阵大小相同的布尔值矩阵,进入过的格子标记为true。如果不满足的情况下,
 * 需要进行回溯,此时,要将当前位置的布尔值标记回false。(所谓的回溯无非就是对使用过的字符进行标记和处理后的去标记)
 *
 * @Description
 */
public class Test10 {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length < 1 || board[0].length < 1 || word == null) return false;
        //矩阵的行号和列号
        int rows = board.length - 1;
        int cols = board[0].length - 1;
        //记录已经访问过的位置
        boolean[] visit = new boolean[rows*cols];
        int pathLength = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (existCore(board,rows,cols,i,j,word,pathLength,visit)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean existCore(char[][] board, int rows, int cols, int i, int j, String word, int pathLength, boolean[] visit) {
        boolean hasPath = false;
        if ((i >= 0) && (i < rows) && (j >= 0) && (j < cols) && board[(i * cols) + j].equals(word.charAt(pathLength)) && !visit[i * cols + j]){
            ++pathLength;
            visit[i*cols + j] = true;
            hasPath = existCore(board, rows, cols, i - 1, j, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i + 1, j, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i, j - 1, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i, j + 1, word, pathLength + 1, visit);
            if (!hasPath){
                --pathLength;
                visit[i*cols + j] = false;
            }
        }
        return hasPath;
    }

    public static void main(String[] args) {

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值