leetcode------Word Search
标题: | Word Search |
通过率: | 20.0% |
难度: | 中等 |
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
.
需要尝试从每一个位置起开始遍历,每次向四个方向开始遍历,如果四个方向都不满足时要将走过的路径回复,边界问题看代码:
用一个index记录查了多少个了。
迭代算法依然没有知道突破口:
1 public class Solution { 2 private int m,n; 3 public boolean exist(char[][] board, String word) { 4 m=board.length; 5 n=board[0].length; 6 boolean [][] visted=new boolean[m][n]; 7 for(int i=0;i<m;i++) 8 for(int j=0;j<n;j++){ 9 if(dfs(board,word,0,i,j,visted)) 10 return true; 11 } 12 return false; 13 } 14 public boolean dfs(char[][] board, String word,int index,int startx,int starty,boolean [][] visted){ 15 if(index==word.length())return true; 16 if(startx<0||startx>=m||starty<0||starty>=n)return false; 17 if(visted[startx][starty])return false; 18 if(board[startx][starty]!=word.charAt(index))return false; 19 visted[startx][starty]=true; 20 boolean res=dfs(board,word,index+1,startx+1,starty,visted)||dfs(board,word,index+1,startx-1,starty,visted)||dfs(board,word,index+1,startx,starty+1,visted)||dfs(board,word,index+1,startx,starty-1,visted); 21 visted[startx][starty]=false; 22 return res; 23 } 24 }