leetcode------Word Search
生活随笔
收集整理的這篇文章主要介紹了
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?=
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 }?
轉載于:https://www.cnblogs.com/pkuYang/p/4349936.html
總結
以上是生活随笔為你收集整理的leetcode------Word Search的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怀孕做梦梦到蛇被打死是什么意思
- 下一篇: HIVE 一行转多行输出办法