79. 单词搜索https://leetcode-cn.com/problems/word-search/
难度中等1077
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
和word
仅由大小写英文字母组成
进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board
更大的情况下可以更快解决问题?
通过次数234,054提交次数509,970
class Solution {
int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
public boolean exist(char[][] board, String word) {
boolean[][] vis = new boolean[board.length][board[0].length];
for(int i=0;i<board.length;i++)
{
for(int j=0;j<board[0].length;j++)
{
if(find(board,word,vis,i,j,0)==true) return true;
}
}
return false;
}
boolean find(char[][] board, String word,boolean [][] vis,int x,int y,int n)
{
if(board[x][y]!= word.charAt(n)) return false;
else if(n == word.length()-1) return true;
boolean re = false;
vis[x][y] = true;
for(int[] d:dir)
{
int newX = x+d[0],newY = y+d[1];
if(newX>=0 && newY>=0 && newX<board.length && newY<board[0].length && !vis[newX][newY])
{
re = find(board,word,vis,newX,newY,n+1);
if(re==true) break;
}
}
vis[x][y] = false;
return re;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69123.html