79. 单词搜索 Java解法

这题同时也是剑指Offer第二版的第12题,我原来写的那个代码实在是太难看了。
在看了剑指Offer中的C++的代码后,我改写成了Java的代码。
这里是典型回溯思想,居然是的方式就是深度优先搜索。

79. 单词搜索

https://leetcode-cn.com/problems/word-search/

任意一个元素都是可以开始的起点,所以,最起码一次每个元素一次遍历。
如果元素符合题目的要求,那么就开始判断它周围的四个元素是否满足要求,如果满足要求的话,就从这个元素继续往下走,当然我们需要要给一个记录是否走过的路径。
当然,知道思想和可以写出正确的代码是两码事,所以,我们来看看正确的代码。

class Solution {
    private int rowNum = 0;
    private int colNum = 0;
    boolean[][] visited = null;
    String word = null;
    char[][] board = null;
    public boolean exist(char[][] board, String word) {
        // 判空操作。
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        rowNum = board.length;
        colNum = board[0].length;
        this.word= word;
        this.board = board;
        visited = new boolean[rowNum][colNum];
        for (int i = 0; i < rowNum; ++i) {
            for (int j = 0; j < colNum; ++j) {
                if (existCore(i , j, 0 )) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean existCore(int row, int col, int index) {
        if (index == word.length()) {
            return true;
        }
        boolean hasPath = false;
        if (row >= 0 && row < rowNum && col >= 0 && col < colNum && !visited[row][col]
            && word.charAt(index) == board[row][col]) {
            ++index;
            visited[row][col] = true;
            // 判断四个点中是否满足条件。
            hasPath = existCore(row - 1, col, index)
                || existCore(row + 1, col, index)
                || existCore(row, col - 1, index)
                || existCore(row, col + 1, index);
            // 如果四个点都没满足,那么就要退回上一个点,吧走过的点置为false
            if (!hasPath) {
                --index;
                visited[row][col] = false;
            }
        }
        return hasPath;
    }
}

以上的代码,效果还不错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值