LeetCode-212.Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

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

Example:

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

Output: ["eat","oath"]

Note:
You may assume that all inputs are consist of lowercase letters a-z.

使用dfs

 1 class Solution {//dfs my
 2     public List<String> findWords(char[][] board, String[] words) {
 3         Set<String> set = new HashSet<>(Arrays.asList(words));//数组可能会重复
 4         List<String> list = new ArrayList<>();
 5         if(null==words||0==words.length){
 6             return list;
 7         }
 8         for(String s:set){
 9             if(exist(board,s)){
10                 list.add(s);
11             }
12         }
13         return list;
14     }
15     private boolean exist(char[][] board, String word) {
16         if(null==board||0==board.length){
17             return false;
18         }
19         int row = board.length;
20         int col = board[0].length;
21         boolean[][] flag = new boolean[row][col];
22         char c = word.charAt(0);
23         for (int i = 0; i < row; i++) {
24                 for (int j = 0; j < col; j++) {
25                     if(board[i][j]==c){
26                         flag[i][j]=true;
27                         if(dfs(board,flag,i+1,j,word,1)||dfs(board,flag,i-1,j,word,1)||dfs(board,flag,i,j+1,word,1)||dfs(board,flag,i,j-1,word,1)){
28                             return true;
29                         }
30                         flag[i][j]=false;
31                     }
32                 }
33             }
34         return false;
35     }
36     private boolean dfs(char[][] board, boolean[][] flag,int x,int y,String word,int index){
37         if(index>=word.length()){
38             return true;
39         }
40         if(x<0||y<0||x>=board.length||y>=board[0].length||flag[x][y]){
41             return false;
42         }
43         boolean re = false;
44         if(board[x][y]==word.charAt(index)){
45             flag[x][y]=true;
46             re= dfs(board,flag,x+1,y,word,index+1)||dfs(board,flag,x-1,y,word,index+1)||dfs(board,flag,x,y+1,word,index+1)||dfs(board,flag,x,y-1,word,index+1);
47             flag[x][y]=false;
48         }
49         return re;
50     }
51 
52 }

相关题

单词搜索 LeetCode79 https://www.cnblogs.com/zhacai/p/10641454.html

实现字典树 LeetCode208 https://www.cnblogs.com/zhacai/p/10640769.html

猜你喜欢

转载自www.cnblogs.com/zhacai/p/10641592.html