您的位置:首页 > 其它

Word Search

2015-11-17 16:37 155 查看
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 =

[

[‘A’,’B’,’C’,’E’],

[‘S’,’F’,’C’,’S’],

[‘A’,’D’,’E’,’E’]

]

word = “ABCCED”, -> returns true,

word = “SEE”, -> returns true,

word = “ABCB”, -> returns false.

Subscribe to see which companies asked this question

public class Solution {
//this is a good problem
public boolean exist(char[][] board, String word) {
if(board == null || word == null || word.length() == 0)
return false;

for(int i =0; i < board.length; i ++) {
for(int j = 0; j < board[0].length; j++) {
if(dfs(board, i, j, word, 0, new boolean[board.length][board[0].length]))
return true;
}
}
return false;
}

private boolean dfs(char[][] board, int i, int j, String word, int index, boolean[][] isVisited) {
if(word.length() == index)
return true;
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index) || isVisited[i][j])
return false;

isVisited[i][j] = true;
if(dfs(board, i - 1, j, word, index + 1, isVisited))
return true;

if( dfs(board, i + 1, j, word, index + 1, isVisited))
return true;

if( dfs(board, i, j - 1, word, index + 1, isVisited))
return true;

if( dfs(board, i, j + 1, word, index + 1, isVisited))
return true;
//this statement is equal to the four statement above
// boolean res = dfs(board, i - 1, j, word, index + 1, isVisited) || dfs(board, i + 1, j, word, index + 1, isVisited) ||
//               dfs(board, i, j - 1, word, index + 1, isVisited) || dfs(board, i, j + 1, word, index + 1, isVisited);
isVisited[i][j] = false;
return false;
// return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: