Skip to content

Instantly share code, notes, and snippets.

@zwfang
Last active December 7, 2018 08:41
Show Gist options
  • Save zwfang/fb7d3e238565deb64225b2ff1e70521e to your computer and use it in GitHub Desktop.
Save zwfang/fb7d3e238565deb64225b2ff1e70521e to your computer and use it in GitHub Desktop.
word search
#!/usr/bin/env python3
"""
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.
"""
import copy
class Solution:
def __init__(self):
self.visited = []
self.d = [[-1,0],[0,1],[1,0],[0,-1]]
self.m = 0
self.n = 0
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
self.m = len(board)
self.n = len(board[0])
self.visited = copy.deepcopy(board)
for i in range(self.m):
for j in range(self.n):
self.visited[i][j] = False
for i in range(self.m):
for j in range(self.n):
if self.searchWord(board, word, 0, i, j):
return True
return False
def searchWord(self, board, word, index, startx, starty):
if index == len(word) - 1:
return board[startx][starty] == word[index]
if board[startx][starty] == word[index]:
self.visited[startx][starty] = True
for i in range(4):
newx = startx + self.d[i][0]
newy = starty + self.d[i][1]
if self.inArea(newx, newy) and not self.visited[newx][newy] and self.searchWord(board, word, index+1, newx, newy):
return True
self.visited[startx][starty] = False
return False
def inArea(self, x, y):
return x >= 0 and x < self.m and y >= 0 and y < self.n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment