【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:

【LeetCode】212. Word Search II 单词搜索 II(Hard)(JAVA)_第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:

【LeetCode】212. Word Search II 单词搜索 II(Hard)(JAVA)_第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 findWords(char[][] board, String[] words) {
        List 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 每日一题更新

你可能感兴趣的:(Leetcode,字符串,leetcode,java,数据结构,面试)