【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"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
题解:实现一个DFS函数 private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited) ,从(i,j)出开始搜索串left,visited数组记录某个位置是否包含在当前搜索的路径中,因为每个字符只能被使用一次。
代码如下:
1 public class Solution { 2 private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited){ 3 //if we have found one path 4 if(left.equals("")) 5 return true; 6 7 //look around point(i,j) see if we can find next char 8 char next = left.charAt(0); 9 if(i-1>=0 && !visited[i-1][j] && board[i-1][j]== next ){ 10 visited[i-1][j] = true; 11 if(canFind(board, i-1, j, left.substring(1),visited)) 12 return true; 13 visited[i-1][j]= false; 14 } 15 16 if(j-1>=0 && !visited[i][j-1] && board[i][j-1]== next ){ 17 visited[i][j-1] = true; 18 if(canFind(board, i, j-1, left.substring(1),visited)) 19 return true; 20 visited[i][j-1]= false; 21 } 22 23 if(i+1 < board.length && !visited[i+1][j] && board[i+1][j]== next ){ 24 visited[i+1][j] = true; 25 if(canFind(board, i+1, j, left.substring(1),visited)) 26 return true; 27 visited[i+1][j]= false; 28 } 29 30 31 if(j+1 < board[0].length && !visited[i][j+1] && board[i][j+1]== next ){ 32 visited[i][j+1] = true; 33 if(canFind(board, i, j+1, left.substring(1),visited)) 34 return true; 35 visited[i][j+1]= false; 36 } 37 38 return false; 39 } 40 public boolean exist(char[][] board, String word) { 41 if(word == null || word.length() == 0) 42 return true; 43 if(board.length == 0) 44 return false; 45 46 int m = board.length; 47 int n = board[0].length; 48 char now = word.charAt(0); 49 boolean[][] visited = new boolean[m][n]; 50 51 //search board for our first char in word 52 for(int i = 0;i < m;i++){ 53 for(int j = 0;j < n;j ++){ 54 if(board[i][j]== now ){ 55 visited[i][j]= true; 56 if(canFind(board, i, j, word.substring(1),visited)) 57 return true; 58 visited[i][j]= false; 59 } 60 } 61 } 62 63 return false; 64 } 65 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了