Write code to solve: Problem Description In the CCC Word Hunt, words are hidden in a…
- User
Write code to solve: Problem Description In the CCC Word Hunt, words are hidden in a grid of letters. The letters of a hidden word always appear in order on horizontal, vertical, or diagonal line segments in one of two ways. One way is for the letters of a word to appear on one line segment. The other way is for the letters of a word to appear on one line segment up to some letter and then on a second line segment that forms a right angle at this letter. Given a grid of letters and a single word to search for, your job is to determine the number of times that particular word is hidden in the grid. Input Specification The first line of input will contain a string of distinct uppercase letters, W, representing the word you are to search for in the grid. The length of W will be at least two. The second line of input will be an integer R (1 R 100), where R is the number of rows in the grid. The third line of input will be an integer C (1 C 100), where C is the number of columns in the grid. The remaining input will provide the letters in the grid. It will consist of R lines, where each line contains C uppercase letters separated by single spaces
- Assistant
Here is a possible solution in Python:
def count_word(grid, word): count = 0 rows = len(grid) cols = len(grid[0]) for i in range(rows): for j in range(cols): # Check if word starts at (i, j) position if grid[i][j] == word[0]: # Check horizontal right if j + len(word) <= cols and grid[i][j:j+len(word)] == word: count += 1 # Check horizontal left if j - len(word) >= -1 and grid[i][j-len(word)+1:j+1][::-1] == word[::-1]: count += 1 # Check vertical down if i + len(word) <= rows: match = True for k in range(i, i+len(word)): if grid[k][j] != word[k-i]: match = False break if match: count += 1 # Check vertical up if i - len(word) >= -1: match = True for k in range(i, i-len(word), -1): if grid[k][j] != word[i-k]: match = False break if match: count += 1 # Check diagonal down right if i + len(word) <= rows and j + len(word) <= cols: match = True for k in range(len(word)): if grid[i+k][j+k] != word[k]: match = False break if match: count += 1 # Check diagonal up left if i - len(word) >= -1 and j - len(word) >= -1: match = True for k in range(len(word)): if grid[i-k][j-k] != word[k]: match = False break if match: count += 1 return count # Read input word = input() rows = int(input()) cols = int(input()) grid = [] for _ in range(rows): row = input().split() grid.append(row) # Call the function and print the result result = count_word(grid, word) print(result)This solution works by iterating over each position in the grid and checking if the word starts at that position. It checks for matches on horizontal, vertical, and diagonal segments both in the forward and backward directions. The function
count_wordreturns the number of occurrences of the word in the grid.