A golang solution


  • 0
    N
    type coordinate struct {
    	x, y int
    }
    
    func findWord(c coordinate, board [][]byte, word string, m map[coordinate]struct{}, level int) bool {
    	if level == 0 {
    		return true
    	}
    
    	for _, v := range []coordinate{
    				{c.x - 1, c.y},
    				{c.x + 1, c.y},
    				{c.x, c.y - 1},
    				{c.x, c.y + 1}} {
    		if v.x >= 0 && v.x < len(board) && v.y >= 0 && v.y < len(board[v.x]) {
    			if _, ok := m[v]; !ok && word[len(word) - level] == board[v.x][v.y] {
    				m[v] = struct{}{}
    				if findWord(v, board, word, m, level - 1) {
    					return true
    				} else {
    					delete(m, v)
    				}
    			}
    		}
    	}
    
    	return false
    }
    
    func exist(board [][]byte, word string) bool {
    	if len(word) <= 0 {
    		return true
    	}
    
    	m := make(map[coordinate]struct{})
    	for i := 0; i < len(board); i++ {
    		for j := 0; j < len(board[i]); j++ {
    			if board[i][j] == word[0] {
    				m[coordinate{i, j}] = struct {}{}
    				if findWord(coordinate{i, j}, board, word, m, len(word) - 1) {
    					return true
    				} else {
    					delete(m, coordinate{i, j})
    				}
    			}
    		}
    	}
    
    	return false
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.