其他分享
首页 > 其他分享> > Leetcode 79. 单词搜索

Leetcode 79. 单词搜索

作者:互联网

79. 单词搜索 - 力扣(LeetCode)

 

 思路 还是回溯

func exist(board [][]byte, word string) bool {
	if len(board) < 1 || len(board[0]) > 6 || len(word) > 15 || len(word) < 1 {
		return false
	}
	var backTracking func(board [][]byte, x, y int, wordIndex int, temp string) bool
	backTracking = func(board [][]byte, x, y int, wordIndex int, temp string) bool {
		if wordIndex == len(word) {
			if temp == word {
				return true
			} else {
				return false
			}
		}

		if x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) && board[x][y] == byte(word[wordIndex]) {
			temp = temp + string(board[x][y])
			board[x][y] += 100
			res1 := backTracking(board, x+1, y, wordIndex+1, temp)
			res2 := backTracking(board, x-1, y, wordIndex+1, temp)
			res3 := backTracking(board, x, y+1, wordIndex+1, temp)
			res4 := backTracking(board, x, y-1, wordIndex+1, temp)
			board[x][y] -= 100
			return res1 || res2 || res3 || res4
		}
		return false
	}

	for i := 0; i < len(board); i++ {
		for j := 0; j < len(board[0]); j++ {
			if board[i][j] == word[0] {
				if backTracking(board, i, j, 0, "") {
					return true
				}
			}
		}
	}
	return false
}

  

标签:return,temp,wordIndex,len,单词,board,word,Leetcode,79
来源: https://www.cnblogs.com/lizhengnan/p/16251931.html