Notes title leetcode brush (Golang) -. 79 Word Search

79. Word Search

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’]
]

Word = GIVEN "ABCCED", return to true.
GIVEN Word = "the SEE", return to true.
GIVEN Word = "ABCB", return false.
Problem-solving ideas, flower sauce Gangster

var rows int
var cols int

func exist(board [][]byte, word string) bool {
	if len(board) == 0 || len(board[0]) == 0 {
		return false
	}

	rows = len(board)
	cols = len(board[0])
	for i := 0; i < rows; i++ {
		for j := 0; j < cols; j++ {
			if dfs(board, 0, i, j, word, []byte{}) {
				return true
			}
		}
	}
	return false
}

func dfs(graph [][]byte, index int, r int, c int, target string, path []byte) bool {
	if r < 0 || r == rows || c < 0 || c == cols || index >= len(target) || graph[r][c] != target[index] {
		return false
	}
	fmt.Println(string(target[index]), graph[r][c], target[index], graph[r][c] == target[index])
	if len(path)+1 == len(target) {
		return true
	}
	//四个方向
	curr := graph[r][c]
	graph[r][c] = 0
	res := dfs(graph, index+1, r-1, c, target, append(path, graph[r][c])) || dfs(graph, index+1, r+1, c, target, append(path, graph[r][c])) || dfs(graph, index+1, r, c-1, target, append(path, graph[r][c])) || dfs(graph, index+1, r, c+1, target, append(path, graph[r][c]))
	graph[r][c] = curr
	return res
}
Published 65 original articles · won praise 0 · Views 352

Guess you like

Origin blog.csdn.net/weixin_44555304/article/details/104290109