【LeetCode】212. Word Search II 单词搜索 II(Hard)(JAVA)

【LeetCode】212. Word Search II 单词搜索 II(Hard)(JAVA)

题目地址: https://leetcode.com/problems/word-search-ii/

题目描述:

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example 1:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]

Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 10^4
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.

题目大意

给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。

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

解题方法

  1. 这一题和判断一个字符串是否在 board 数组里是一样的
  2. 首先 board 的每个位置都可能是开头,如果 word.charAt(0) 和 board[i][j] 相同,就接着判断下一个
  3. 不断递归,判断下一个。难点在于如何避免被遍历过的位置不被重复遍历(因为 board 数组的元素不能被一个字符串重复使用)
  4. 把遍历过的位置置位 0(因为只包含小写字符,所以可以把遍历过的 char 置位 0),返回结果的时候再重置(因为后面的还需要使用)
class Solution {
    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();
        for (int k = 0; k < words.length; k++) {
            boolean flag = false;
            for (int i = 0; i < board.length && !flag; i++) {
                for (int j = 0; j < board[0].length && !flag; j++) {
                    if (fH(board, words[k], 0, i, j)) {
                        res.add(words[k]);
                        flag = true;
                    }
                }
            }
        }
        return res;
    }

    int[][] ori = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    public boolean fH(char[][] board, String word, int start, int i, int j) {
        if (start >= word.length()) return true;
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(start)) return false;
        char temp = board[i][j];
        board[i][j] = 0;
        boolean flag = false;
        for (int k = 0; k < ori.length && !flag; k++) {
            flag = fH(board, word, start + 1, i + ori[k][0], j + ori[k][1]);
        }
        board[i][j] = temp;
        return flag;
    }
}

执行耗时:2 ms,击败了95.73% 的Java用户
内存消耗:36.9 MB,击败了92.01% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值