您的位置:首页 > 其它

【leetcode刷题笔记】Word Search

2014-07-24 10:47 399 查看
Given a 2D board and a word, find if the word exists in the grid.

The word can 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.

For example,
Given board =

[
["ABCE"],
["SFCS"],
["ADEE"]
]


word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.

题解:实现一个DFS函数 private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited) ,从(i,j)出开始搜索串left,visited数组记录某个位置是否包含在当前搜索的路径中,因为每个字符只能被使用一次。

代码如下:

public class Solution {
private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited){
//if we have found one path
if(left.equals(""))
return true;

//look around point(i,j) see if we can find next char
char next = left.charAt(0);
if(i-1>=0 && !visited[i-1][j] && board[i-1][j]== next ){
visited[i-1][j] = true;
if(canFind(board, i-1, j, left.substring(1),visited))
return true;
visited[i-1][j]= false;
}

if(j-1>=0 && !visited[i][j-1] && board[i][j-1]== next ){
visited[i][j-1] = true;
if(canFind(board, i, j-1, left.substring(1),visited))
return true;
visited[i][j-1]= false;
}

if(i+1 < board.length && !visited[i+1][j] && board[i+1][j]== next ){
visited[i+1][j] = true;
if(canFind(board, i+1, j, left.substring(1),visited))
return true;
visited[i+1][j]= false;
}

if(j+1 < board[0].length && !visited[i][j+1] && board[i][j+1]== next ){
visited[i][j+1] = true;
if(canFind(board, i, j+1, left.substring(1),visited))
return true;
visited[i][j+1]= false;
}

return false;
}
public boolean exist(char[][] board, String word) {
if(word == null || word.length() == 0)
return true;
if(board.length == 0)
return false;

int m = board.length;
int n = board[0].length;
char now = word.charAt(0);
boolean[][] visited = new boolean[m]
;

//search board for our first char in word
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j ++){
if(board[i][j]== now ){
visited[i][j]= true;
if(canFind(board, i, j, word.substring(1),visited))
return true;
visited[i][j]= false;
}
}
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: