Word Search
一、迷宫问题解决了
http://my.oschina.net/findurl/blog/343774
二、下面这个单词搜索问题
For example,
Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
其实也就是迷宫问题中的一个通道。
如何解决那?
其实就是单词的首字母应该是迷宫的入口,而单词的结尾就是迷宫问题的出口
/**
* 搜索一个二维数组中的单词
*
* @author WZ 20141113
*/
public class SearchWord {
char searchArray[][]={
{'a','b','c','e'},
{'s','f','c','f'},
{'a','d','e','e'}
};
//方向
int move[][] = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
//存在
boolean isHas=false;
//位置移动
int d=0;
public void search(String word){
//1.首先找到位置
for(int i=0;i<3;i++)
for(int j=0;j<4;j++){
if(searchArray[i][j]==word.charAt(0)){
isHasWord(i,j,word);
if(isHas){
System.out.println("找到了("+i+","+j+")");
return;
}
}
}
}
/*
* 搜索单词
*/
public void isHasWord(int i,int j,String word){
System.out.println(searchArray[i][j]);
//找到了
if((searchArray[i][j]==word.charAt(word.length()-1))&&d==word.length()-1){
isHas=true;
return;
}
for(int k=0;k<8;k++){
int m=i+move[k][0];
int n=j+move[k][1];
//如果到边界了就结束了
if(m>2||m<0||n>3||n<0||d>word.length()-1)
return;
//下一个匹配的话就进入 不然换方向
if(searchArray[m][n]==word.charAt(d+1)){
d++;//位置移动下一位
isHasWord(m,n,word);
if(isHas)
return;
}
}
}
public static void main(String[] args) {
SearchWord sw=new SearchWord();
sw.search("be");
// sw.search("bfc");
}
}