日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 79. Word Search

發布時間:2023/11/29 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 79. Word Search 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原題鏈接在這里:https://leetcode.com/problems/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?=

[['A','B','C','E'],['S','F','C','S'],['A','D','E','E'] ]

word?=?"ABCCED", -> returns?true,
word?=?"SEE", -> returns?true,
word?=?"ABCB", -> returns?false.

題解:

類似N-Queens. dfs, 終止條件若能走到index == word.length(), 返回true.

若是做不到就是中間出現了越界或者不等,返回false.

用之前要把used 對應位置改為true, 用完后記得把used 對應位置改為false.?

最后返回res.

Time Complexity: O(m^2 * n^2). ?對于board每一個點search都是一次dfs, dfs用了O(V+E), 矩陣表示時就是O(m*n). 并且board一共有m*n個點.

Space: O(m*n). 因為用了used存儲。這里m=board.length, n = board[0].length.

AC Java:

1 public class Solution { 2 public boolean exist(char[][] board, String word) { 3 if(word==null || word.length()==0) 4 return true; 5 if(board==null || board.length==0 || board[0].length==0) 6 return false; 7 boolean[][] used = new boolean[board.length][board[0].length]; 8 for(int i=0;i<board.length;i++) 9 { 10 for(int j=0;j<board[0].length;j++) 11 { 12 if(search(board,word,0,i,j,used)) 13 return true; 14 } 15 } 16 return false; 17 } 18 private boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used) 19 { 20 if(index == word.length()) 21 return true; 22 if(i<0 || j<0 || i>=board.length || j>=board[0].length || used[i][j] || board[i][j]!=word.charAt(index)) 23 return false; 24 used[i][j] = true; 25 boolean res = search(board,word,index+1,i-1,j,used) 26 || search(board,word,index+1,i+1,j,used) 27 || search(board,word,index+1,i,j-1,used) 28 || search(board,word,index+1,i,j+1,used); 29 used[i][j] = false; 30 return res; 31 } 32 }

?跟上Word Search II

轉載于:https://www.cnblogs.com/Dylan-Java-NYC/p/4944270.html

總結

以上是生活随笔為你收集整理的LeetCode 79. Word Search的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。