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.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ]Return
["eat","oath"]
.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
dfs搜索,开始遍历的时候先建立一个索引表,比如我要找“oath",第一个字母是‘o',建立26个索引分别存放以'a'-'z'开头的字母在board中的位置。这样搜索的时候不用遍历board,减小复杂度。
因为每次搜索单词”互不干扰“,也就是如果我搜索”oath",在这之后搜索"ath"应该要能搜索到,所以搜索的时候是否使用的标志位还要进行回溯。
测试数据比较狠,改为倒着搜才pass
int m,n;
int[] xoff={1,-1,0,0};
int[] yoff={0,0,1,-1};
boolean[][] onstack;
public List<String> findWords(char[][] board, String[] words)
{
int strslen=words.length;
ArrayList<String> retarr=new ArrayList<>(strslen);
if(strslen<1)
return retarr;
m=board.length;
if(m==0)
return retarr;
n=board[0].length;
ArrayList<Integer>[] indexs=new ArrayList[26];
HashMap<Integer, Integer> hashmap=new HashMap<>(128);
onstack=new boolean[m][n];
for(int i=0;i<26;i++)
indexs[i]=new ArrayList<>();
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
int index=board[i][j]-'a';
indexs[index].add(i);
indexs[index].add(j);
}
for(String s:words)
{
int hash=s.hashCode();
if(!hashmap.containsKey(hash))
hashmap.put(hash, hashmap.size());
else {
continue;
}
int lastchar=s.charAt(s.length()-1)-'a';
int size=indexs[lastchar].size();
for(int i=0;i<size;i+=2)
{
int x=indexs[lastchar].get(i);
int y=indexs[lastchar].get(i+1);
if(dfs(x, y, s, s.length()-1, board))
{
retarr.add(s);
break;
}
}
}
return retarr;
}
public boolean dfs(int x,int y,String s,int d,char[][] board)
{
if(d==0)
return true;
onstack[x][y]=true;
char c=s.charAt(d-1);
for(int i=0;i<4;i++)
{
int xx=x+xoff[i];
int yy=y+yoff[i];
if(xx>=0&&xx<m&&yy>=0&&yy<n&&!onstack[xx][yy]&&board[xx][yy]==c)
if(dfs(xx, yy,s,d-1,board))
{
onstack[x][y]=false;
return true;
}
}
onstack[x][y]=false;
return false;
}