leetcode79. 单词搜索(回溯算法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode79. 单词搜索(回溯算法)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)二維網(wǎng)格和一個(gè)單詞,找出該單詞是否存在于網(wǎng)格中。
單詞必須按照字母順序,通過相鄰的單元格內(nèi)的字母構(gòu)成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個(gè)單元格內(nèi)的字母不允許被重復(fù)使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
給定 word = “ABCCED”, 返回 true
給定 word = “SEE”, 返回 true
給定 word = “ABCB”, 返回 false
代碼
class Solution {boolean[][] vis;public boolean exist(char[][] board, String word) {int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};int n=board.length,m=board[0].length;vis=new boolean[n][m];for(int i=0;i<n;i++)for(int j=0;j<m;j++){if(checkExist(board,word,dir,0,i,j))return true;}return false;}public boolean checkExist(char[][] board, String word, int[][] dir,int loc,int x,int y) {if(board[x][y]!=word.charAt(loc))return false;if(loc==word.length()-1) return true;vis[x][y]=true;//標(biāo)記for(int[] d:dir){int nextX=x+d[0],nextY=y+d[1];if (nextX < 0 || nextX >= board.length || nextY < 0 || nextY >= board[0].length||vis[nextX][nextY])continue;if(checkExist(board, word, dir, loc+1, nextX, nextY)) return true;}vis[x][y]=false;//回溯return false;} }總結(jié)
以上是生活随笔為你收集整理的leetcode79. 单词搜索(回溯算法)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到狗咬脖子什么预兆
- 下一篇: leetcode94. 二叉树的中序遍历