단어가 그리드에있는 경우 2 차원 보드와 단어 감안할 때, 찾을 수 있습니다.
단어는 "인접"세포는 그 수평 또는 수직으로 인접이다 순차적으로 인접 셀의 문자로 구성 될 수있다. 같은 문자 셀은 한 번 이상 사용할 수 없습니다.
예:
보드 =
[
[ 'A', 'B', 'C', 'E'],
[ 'S', 'F', 'C', 'S'],
[ 'A', 'D', 'E ','E ']
]
워드 = true로 반환합니다. "ABCCED"GIVEN
true로 돌아갑니다., 워드 = "를 SEE"GIVEN
말씀 = "ABCB"반환 거짓 GIVEN.
아이디어를 문제 해결, 꽃 소스 갱스
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
}