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
1 public class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(word == null || word.length() == 0) return true; 4 boolean[][] visit = new boolean[board.length][board[0].length]; 5 char[] words = word.toCharArray(); 6 for(int i = 0; i < board.length; i++){ 7 for(int j = 0; j < board[0].length; j++){ 8 if(BFS(board,visit,words,0,i,j)) return true; 9 } 10 } 11 return false; 12 } 13 14 public boolean BFS(char[][] board,boolean[][] visit, char[] word, int len, int row, int col){ 15 if(len == word.length){ 16 return true; 17 } 18 if(row < 0 || row == board.length || col < 0 || col == board[row].length) return false; 19 if(board[row][col] != word[len]) return false; 20 if(!visit[row][col]){ 21 visit[row][col] = true; 22 boolean tmp = BFS(board,visit,word,len+1,row,col+1) || 23 BFS(board,visit,word,len+1,row,col-1) || BFS(board,visit,word,len+1,row+1,col) || 24 BFS(board,visit,word,len+1,row-1,col); 25 visit[row][col] = false; 26 return tmp; 27 }else return false; 28 } 29 }
BFS 方法的代码逻辑等二刷时候再修改学习下。
时间: 2024-10-13 01:02:37