標籤:style blog http color strong os
Word Search
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,注意判斷邊界
1 public class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(board == null || board.length == 0|| word == null ) return false; 4 int height = board.length; 5 int width = board[0].length; 6 if(height * width < word.length()) return false; 7 for(int i = 0; i < height; i++){ 8 for(int j = 0; j < width; j++){ 9 if(board[i][j] == word.charAt(0)){10 if(dfs(board,word.substring(1),i,j)) return true;11 }12 }13 }14 return false;15 }16 private boolean dfs(char[][] board,String left,int row,int column){17 if(left.length() == 0){18 return true;19 }20 int height = board.length;21 int width = board[0].length;22 char c = board[row][column];23 board[row][column] = ‘ ‘;24 if( column > 0 && board[row][column - 1] == left.charAt(0)){//go left25 if( dfs(board, left.substring(1), row, column - 1)) return true;26 }27 if( column < width - 1 && board[row][column + 1] == left.charAt(0)){//go right28 if( dfs(board, left.substring(1), row, column + 1)) return true;29 }30 if( row > 0 && board[row - 1][column] == left.charAt(0)){//go up31 if( dfs(board, left.substring(1), row - 1, column) ) return true;32 }33 if( row < height - 1 && board[row + 1][column] == left.charAt(0)){//go down34 if( dfs(board, left.substring(1), row + 1, column)) return true;35 }36 board[row][column] = c;37 return false;38 }39 }
其實這道題這種做法是不嚴謹的,因為題中並未說明字串中不包含空格,事實上最好開闢一個標記矩陣,來標記哪些點是否已經匹配過。
我的演算法中對上下左右四個方向進行了直接的判斷,我同學的做法,用一個數組來標記走向,很值得借鑒。戳這裡。