Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local starts = {}; --store where each character is
- local grid = {}; --stores the grid of characters
- --HANDLING INPUT
- local n = io.read("*number");
- local m = io.read("*number"); io.read("*line");
- for i = 1, n do
- local line = io.read("*line");
- grid[i] = {};
- for j = 1, line:len(), 2 do
- local char = line:sub(j, j);
- grid[i][j] = {char = char, x = i, y = (j+1)/2};
- if not starts[char] then
- starts[char] = {};
- end
- table.insert(starts[char], {x = i, y = (j+1)/2});
- end
- end
- local scan = function(word)
- local allowed;
- for i = 1, word:len() do
- local letter = word:sub(i, i);
- local validPos = starts[letter];
- --letter is not in grid, return false
- if not validPos then return false end
- local newAllowed = {};
- local found = false;
- for j = 1, #validPos do
- local pos = validPos[j];
- local reachable = not allowed or allowed[pos.x..":"..pos.y];
- if reachable then
- found = true;
- newAllowed[(pos.x-1)..":"..(pos.y)] = true;
- newAllowed[(pos.x+1)..":"..(pos.y)] = true;
- newAllowed[(pos.x)..":"..(pos.y-1)] = true;
- newAllowed[(pos.x)..":"..(pos.y+1)] = true;
- end
- end
- allowed = newAllowed;
- if not found then return false end
- end
- return true;
- end
- for i = 1, m do
- local line = io.read("*line");
- if scan(line) then
- print(line);
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement