题目地址: 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 x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
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用户