[leetcode] word-search
阿新 • • 發佈:2018-11-05
[leetcode] 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”, -> returnstrue,
word =“SEE”, -> returnstrue,
word =“ABCB”, -> returnsfalse.
解題思路:
此題應該使用深度優先遍歷解決。
程式碼:
public class Solution { int row,col; public boolean exist(char[][] board, String word) { row=board.length; col=board[0].length; boolean[][] flag=new boolean[row][col]; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(dfs(board,word,i,j,0,flag)){ return true; } } } return false; } public boolean dfs(char[][] board, String word,int i,int j,int index,boolean[][] flag){ if(index==word.length()){ return true; } if(i<0||j<0||i>=row||j>=col){ return false; } if(flag[i][j]){ return false; } if(board[i][j]!=word.charAt(index)){ return false; } flag[i][j]=true; boolean res=dfs(board,word,i-1,j,index+1,flag)||dfs(board,word,i+1,j,index+1,flag)|| dfs(board,word,i,j-1,index+1,flag)||dfs(board,word,i,j+1,index+1,flag); flag[i][j]=false; return res; } }
注:
深度優先遍歷需要考慮佔用資源的釋放!