leetcode79. 单词搜索(回溯算法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode79. 单词搜索(回溯算法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二維網格和一個單詞,找出該單詞是否存在于網格中。
單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不允許被重復使用。
示例:
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;//標記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;} }總結
以上是生活随笔為你收集整理的leetcode79. 单词搜索(回溯算法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到狗咬脖子什么预兆
- 下一篇: 梦到和妈妈吵架了预示着什么