leetcode刷题笔记(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’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
解题思路,花花酱大佬

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
}

你可能感兴趣的:(golang,leetcode)