LeetCode.79 单词搜索Java

该博客探讨了LeetCode中的79题——单词搜索,重点介绍了如何利用矩阵和深度优先搜索(DFS)结合状态回溯解决此类问题。文中提及偏移量数组在二维平面上的应用,并指出这类搜索算法的代码模式相对稳定。
摘要由CSDN通过智能技术生成

LeetCode.79 单词搜索

在这里插入图片描述
这是一个矩阵回溯算法典型题目,涉及到DFS和状态回溯重置

  1. 偏移量数组在二维平面经常使用的
  2. 对于这种搜索算法,代码编写也相对固定
package com.leetcode.solution;

/**
 * @Author : fanc
 * @Date : 2019-09-03 17:55
 * 单词搜索
 */
public class Solution79 {
    /**
     * 定义变量
     */
    private boolean[][] marked;
    private int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
    private int rows;
    private int cols;
    private char[][] board;
    private String word;

    /**
     * 判断是否在这个位置是否在矩阵里面
     * @param i
     * @param j
     * @return
     */
    private boolean inArea(int i, int j) {
        return i >= 0 && i < rows && j >= 0 && j < cols;
    }

    /**
     * 矩阵递归回溯深度搜索
     * @param i
     * @param j
     * @param wordIndex
     * @return
     */
    private boolean matrixDfs(int i, int j, int wordIndex) {
        if (board[i][j] == word.charAt(wordIndex) && !marked[i][j]) {
            if (wordIndex == word.length() - 1) {
                return true;
            }
            marked[i][j] = true;
            for (int m = 0; m < direction.length; m++) {
                int newX = i + direction[m][0], newY = j + direction[m][1];
                if (inArea(newX, newY) && matrixDfs(newX, newY, wordIndex + 1)) {
                    return true;
                }
            }
            marked[i][j] = false;
        }
        return false;
    }

    /**
     * 对每个矩阵每个点作为起点开始搜索
     * @param board
     * @param word
     * @return
     */
    public boolean exist(char[][] board, String word) {
        this.board = board;
        this.word = word;
        rows = board.length;
        if (rows == 0) {
            return false;
        }
        cols = board[0].length;
        marked = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrixDfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        char[][] board = {{'a', 'a'}};
        String word = "aaa";
        Solution79 solution = new Solution79();
        boolean exist = solution.exist(board, word);
        System.out.println(exist);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值