Leetcode79 Word Search
题目描述
board =[ ['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
思路
根据word的第一个字符(d=0)在二维char数组中匹配,找到起始位置。找到起始位置后,在该位置的左右上下search, 直到找到与word.charAt(d+1)相同的元素。当到达边界以后(即到达最后一行或最后一列)时返回false,当没有找到word.charAt(d+1)匹配的board元素时,返回false. 当d到达word的最后一个元素后,返回true. 设定boolean型变量flag, flag的值为上下左右search或的结果。
keep in mind:search过的board元素应当暂时改为0.
代码
class Solution {
public boolean exist(char[][] board, String word) {
if(board.length==0) return false;
for(int x=0;x<board.length;x++){//row
for(int y=0;y<board[0].length;y++){//columns
if(search(board,word,x,y,0))
return true;
}
}
return false;
}
private boolean search(char[][] board, String word, int x, int y, int d){
if(x<0||x>=board.length||y<0||y>=board[0].length)
return false;
if(word.charAt(d)!=board[x][y])
return false;
if(d==word.length()-1)
return true;
char pre = board[x][y];
board[x][y]=0;
boolean flag = search(board,word,x+1,y,d+1)||search(board,word,x-1,y,d+1)
||search(board,word,x,y+1,d+1)||search(board,word,x,y-1,d+1);
board[x][y]=pre;
return flag;
}
}