单词搜索
给定一个 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
仅由大小写英文字母组成
题解
dfs 深度搜索,逐个寻找单词,思路不难,代码优化的思路比较重要
class Solution {
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public boolean exist(char[][] board, String word) {
int h = board.length, w = board[0].length;
boolean[][] visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
boolean flag = dfs(board, visited, word, 0, i, j);
if (flag) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, boolean[][] visited, String word, int index, int x, int y) {
if(board[x][y] != word.charAt(index)){
return false;
}else if(index == word.length() - 1){
return true;
}
visited[x][y] = true;
for(int[] dir: directions) {
int next_x = x + dir[0];
int next_y = y + dir[1];
if(next_x >= 0 && next_x < board.length && next_y >= 0 && next_y < board[0].length){
if(!visited[next_x][next_y]){
if (dfs(board,visited,word,index + 1,next_x,next_y)) {
return true;
}
}
}
}
visited[x][y] = false;
return false;
}
}
var directions = [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
func exist(board [][]byte, word string) bool {
h, w := len(board), len(board[0])
var visited = make([][]bool, h)
for i := range visited {
visited[i] = make([]bool, w)
}
for i, row := range board {
for j := range row {
flag := dfs(board, visited, word, 0, i, j)
if flag {
return true
}
}
}
return false
}
func dfs(board [][]byte, visited [][]bool, word string, index int, x, y int) bool {
if board[x][y] != word[index] {
return false
}
if index == len(word)-1 {
return true
}
visited[x][y] = true
for _, dir := range directions {
next_x, next_y := x+dir[0], y+dir[1]
if next_x >= 0 && next_x < len(board) && next_y >= 0 && next_y < len(board[0]) && !visited[next_x][next_y] {
flag := dfs(board, visited, word, index+1, next_x, next_y)
if flag {
return true
}
}
}
visited[x][y] = false
return false
}
标签:word,int,return,next,单词,搜索,board,visited
From: https://blog.csdn.net/qq_49288154/article/details/143651332