1. 程式人生 > >Leetcode---單詞搜尋--回溯

Leetcode---單詞搜尋--回溯

單詞搜尋

題目連結:單詞搜尋

分析:
  • 首先我們需要找到和單詞中首字母匹配的下標值,從該點出發,向四周擴散,遞迴搜尋下一個和第二個字母匹配的值,以此類推……
  • 回溯剪枝:如果下標越界、值不匹配、或者該下標已經遍歷過,那麼直接return
  • 這裡需要定義一個輔助陣列來儲存該下標的值是否遍歷過
  • 遍歷該值時將該值的輔助陣列改為true代表遍歷過了,在呼叫完四個遞迴後,應當將該true再置為false,否則影響上層的下一條遞迴
	public boolean exist(char[][] board, String word) {
		
		if(
word.length()>board.length*board[0].length) { return false; } boolean[][] temp = new boolean[board.length][board[0].length]; char[] cs = word.toCharArray(); for(int i=0;i<board.length;i++) { for(int j=0;j<board[0].length;j++) { if(board[i][j]==cs[0]) { if(traceback(0,i,j,board,
cs,temp)) { return true; } } } } return false; } public boolean traceback(int n,int i,int j,char[][] board,char[] cs,boolean[][] temp) { if(n>=cs.length) { return true; } if(i<board.length&&i>=0&&j<board[0].length&&j>=0&&
board[i][j]==cs[n]&&temp[i][j]==false) { temp[i][j] = true; if(traceback(n+1,i+1,j,board,cs,temp)) return true; if(traceback(n+1,i-1,j,board,cs,temp)) return true; if(traceback(n+1,i,j+1,board,cs,temp)) return true; if(traceback(n+1,i,j-1,board,cs,temp)) return true; temp[i][j] = false; } return false; }