leetCode 79.Word Search (詞搜尋) 解題思路和方法
阿新 • • 發佈:2019-02-07
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
.思路:此題意思是下個字元必須與上個字元相鄰,且不能重複使用。程式碼上難度不大,最主要的是控制搜尋的方向,分別向四個方向搜尋即可。
程式碼如下:
public class Solution { boolean[][] b; public boolean exist(char[][] board, String word) { 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)){ b = new boolean[board.length][board[0].length]; if(search(board,i,j,b,0,word)){ return true; } } } } return false; } //根據首字母的i,j位置查詢word private boolean search(char[][] board,int i,int j,boolean[][] b,int index,String word){ if(board[i][j] != word.charAt(index)){//字元不相等。返回false return false; } if(index == word.length() - 1){//如果到達最後一個,返回true return true; } b[i][j] = true;//標記已使用 if(i > 0 && !b[i-1][j] && search(board,i-1,j,b,index+1,word)){//如果i>0,且i-1的值沒有被使用,搜尋 return true; } if(i < board.length-1 && !b[i+1][j] && search(board,i+1,j,b,index+1,word)){//如果沒有邊界,且i+1的值沒有被使用,搜尋 return true; } if(j > 0 && !b[i][j-1] && search(board,i,j-1,b,index+1,word)){//如果j>0,且j-1的值沒有被使用,搜尋 return true; } if(j < board[0].length-1 && !b[i][j+1] && search(board,i,j+1,b,index+1,word)){//如果沒到邊界,且j+1的值沒有被使用,搜尋 return true; } b[i][j] = false; return false; } }