79. Word Search
程序员文章站
2022-03-08 11:33:03
...
题目描述:
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.
Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
class Solution {
public boolean exist(char[][] board, String word) {
//考虑使用深度搜索
int m = board.length;
int n = board[0].length;
//创建访问标记数组
int[][] visited = new int[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
visited[i][j] = 0;
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
if(help(board, word, i,j,0,visited))
return true;
}
}
return false;
}
public boolean help(char[][] board, String word, int i, int j, int index, int[][] visited){
if(index == word.length()) return true;
if(i<0||j<0||i>=board.length||j>=board[0].length) return false;
if (visited[i][j] == 1) return false;
if(board[i][j] != word.charAt(index)) return false;//剪枝
visited[i][j] = 1;
boolean res = help(board, word, i-1,j, index+1,visited)||
help(board, word, i+1,j, index+1,visited)||
help(board, word, i, j-1,index+1,visited)||
help(board, word, i, j+1,index+1,visited);
visited[i][j] = 0;
return res;
}
}
注意:
- 剪枝操作
- ||的短路操作(四种情况只要出现一个为真就短路返回,不再深搜)
推荐阅读
-
php在程序中将网页生成word文档并提供下载的代码
-
C#操作word的方法示例
-
Python使用win32com模块实现数据库表结构自动生成word表格的方法
-
php array_search() 函数使用
-
荐 Java刷题笔记15:不同的二叉搜索树( Unique Binary Search Trees)
-
python正则表达式match和search用法实例
-
《java核心技术:卷1》PDF版 和 Word版下载
-
C# 将Word转为PDF、XPS、Epub、RTF(基于Spire.Cloud.Word.SDK)
-
将“自动套用格式”命令放在Word2010快速访问工具栏
-
在Word2010中将制表位转换成表格