美文网首页
Leetcode 精选之搜索(单词搜索)

Leetcode 精选之搜索(单词搜索)

作者: Kevin_小飞象 | 来源:发表于2020-04-03 14:26 被阅读0次

题目描述

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

提示:

  • board 和 word 中只包含大写和小写英文字母。
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

题目链接:力扣

解题思路

class Solution {
    private final static int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    private int m;
    private int n;

    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() == 0) {
            return true;
        }
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }

        m = board.length;
        n = board[0].length;
        boolean[][] hasVisited = new boolean[m][n];

        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (backtracking(0, r, c, hasVisited, board, word)) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean backtracking(int curLen, int r, int c, boolean[][] visited, final char[][] board, final String word) {
        if (curLen == word.length()) {
            return true;
        }
        if (r < 0 || r >= m || c < 0 || c >= n
                || board[r][c] != word.charAt(curLen) || visited[r][c]) {

            return false;
        }

        visited[r][c] = true;

        for (int[] d : direction) {
            if (backtracking(curLen + 1, r + d[0], c + d[1], visited, board, word)) {
                return true;
            }
        }

        visited[r][c] = false;

        return false;
    }
}

测试结果

image.png

相关文章

  • Leetcode 精选之搜索(单词搜索)

    题目描述 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母...

  • Leetcode 精选之搜索(单词接龙)

    题目描述 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 end...

  • LeetCode-79-单词搜索(Word Search)

    LeetCode-79-单词搜索(Word Search) 79. 单词搜索[https://leetcode-c...

  • leetcode212 单词搜索II

    题目 单词搜索II 暴力解法 暴力解法就是用leetcode79 单词搜索这题的搜索一个单词的dfs方法,挨个搜索...

  • LeetCode 单词搜索

    题目描述: 解题思路:这里考虑到使用字符串,并且设计到字符的搜索,想到采用前缀树来进行存储,并根据前缀树进行搜索 ...

  • 【leetcode】单词搜索

    【leetcode】单词搜索 题目: 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺...

  • Leetcode 精选之搜索(组合)

    题目描述 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例: 题目链接:力扣 ...

  • Leetcode 精选之搜索( 子集)

    题目描述 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子...

  • LeetCode 79.单词搜索

    1、题目 单词搜索 - 力扣(LeetCode) https://leetcode-cn.com/problems...

  • Leetcode 精选之搜索(全排列)

    题目描述 给定一个 没有重复 数字的序列,返回其所有可能的全排列。 示例: 题目链接:力扣 解题思路 测试结果

网友评论

      本文标题:Leetcode 精选之搜索(单词搜索)

      本文链接:https://www.haomeiwen.com/subject/lmmhphtx.html