Skip to content

Instantly share code, notes, and snippets.

@landau
Created September 24, 2013 00:42
Show Gist options
  • Save landau/6678937 to your computer and use it in GitHub Desktop.
Save landau/6678937 to your computer and use it in GitHub Desktop.
Initial filthy solution - need to ditch some shit....
"""
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.
input: ASADB, ABCCED
https://www.codeeval.com/open_challenges/65/
"""
from sys import argv
# Change a char to None if seen
grid = [
list('ABCE'),
list('SFCS'), #(1,1), (2, 1), (2, 2)
list('ADEE')
]
def find(grid, char):
"""
search for all positions of a
add to tuple if reachable from current if present
"""
positions = []
for y in xrange(len(grid)):
for x in xrange(len(grid[y])):
found = grid[y][x]
if found == char:
positions.append((x, y))
return tuple(positions)
c = 0
def next_char(bgrid, grid, position, match):
global c
x, y = position
if not bgrid[y][x]: return ''
# TODO move to open loop
h = len(grid) - 1
w = max([len(vals) for vals in grid]) - 1
bgrid[y][x] = False
string = ''
if c < len(match) and match[c] and grid[y][x] == match[c]:
string += grid[y][x]
c += 1
# move left
if x > 0 and bgrid[y][x - 1]:
string += next_char(bgrid, grid, (x - 1, y), match)
# move right
if x < w and bgrid[y][x + 1]:
string += next_char(bgrid, grid, (x + 1, y), match)
# move up
if y > 0 and bgrid[y - 1][x]:
string += next_char(bgrid, grid, (x, y - 1), match)
# move down
if y < h and bgrid[y + 1][x]:
string += next_char(bgrid, grid, (x, y + 1), match)
return string
# iteration and marking of grid will need to occur multiple times
def make_bool_grid(grid, word):
bool_grid = [[False] * len(row) for row in grid]
# TODO remove dupes
# Iterate through each char in word
# and make value in grid = True if matches
for i in xrange(len(grid)):
for j in xrange(len(grid[i])):
val = grid[i][j]
for char in word:
if val == char:
bool_grid[i][j] = True
break
return bool_grid
for line in open(argv[1], 'r'):
line = line.strip()
positions = find(grid, line[0])
found = False
for pos in positions:
c = 0
string = next_char(make_bool_grid(grid, line), grid, pos, line)
if string == line:
found = True
break
print found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment