严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Word Search I leetcode 原题 amazon onsite特喜欢考

Go down

Word Search I  leetcode 原题 amazon onsite特喜欢考 Empty Word Search I leetcode 原题 amazon onsite特喜欢考

Post by Admin Sun Oct 22, 2017 2:48 pm

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

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

private static boolean DFS(char[][] board, int i, int j, String word, int index){
if(index == word.length())
return true;

if (i < 0 || i>= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index))
return false;

board[i][j] = '#';
boolean rst = DFS(board, i-1, j, word, index+1)
|| DFS(board, i, j-1, word, index+1)
|| DFS(board, i+1, j, word, index+1)
|| DFS(board, i, j+1, word, index+1);
board[i][j] = word.charAt(index);
return rst;
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum