Word Search II


Problem Statement :


Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

 

Example 1:


Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2:


Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
 

Constraints:

m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique.



Solution :



title-img


                            Solution in C :

int insPos = -1;
for (int i = 0; i < indexArrayLen; i++) {
    if (wordsLenArray[indexArray[i]] == seedLen) {
        //find word
        indexArrayLen--;
        
        RetArray[retArrayNum++] = pWords[indexArray[i]];
        wordsLenArray[indexArray[i]] = 0;
        //updatetargetIdxBuf
        int k = 0;
        int pos;
        for (k = 0; k < targetIdxNum[seed[0] - 'a']; k++) {
            if (targetIdxBuf[seed[0] - 'a'][k] == indexArray[i]) {
                pos = k;
                break;
            }
        }
        targetIdxNum[seed[0] - 'a']--;
        if (pos != targetIdxNum[seed[0] - 'a']) {
            for (k = pos; k < targetIdxNum[seed[0] - 'a']; k++)
            {
                targetIdxBuf[seed[0] - 'a'][k] = targetIdxBuf[seed[0] - 'a'][k + 1];
            }
        }
       
        insPos = i;
        break;
    }
}

if (indexArrayLen == 0) {
    return;
}
else if(insPos != -1 && insPos <  indexArrayLen && seedLen !=1 ){
    for (int k = insPos; k < indexArrayLen; k++)
    {
        indexArray[k] = indexArray[k + 1];
    }

}

trace[row][col] = 1;
// 상하좌우로 계속 이동한다.
//상
if (row - 1 >= 0 && trace[row - 1][col] != 1){
    char filter = pBoard[row - 1][col];
    //indexArray 중에서 filter에 맞는 것의 개수를 찾자.
    seed[seedLen] = filter;
    seed[seedLen + 1] = 0;
    int* idxArray = (int*)malloc(indexArrayLen * sizeof(int));
    int idxNum = 0;
    for (int k = 0; k < indexArrayLen; k++) {
        if (wordsLenArray[indexArray[k]] > seedLen) {
            if (filter == pWords[indexArray[k]][seedLen]) {
                idxArray[idxNum++] = indexArray[k];
            }
        }
    }
    if (idxNum > 0)
        searchWord2(seed, seedLen + 1, idxArray, idxNum, row - 1, col);
    free(idxArray);
}

// 하 
if (row + 1 < H && trace[row + 1][col] != 1) {
    char filter = pBoard[row + 1][col];
    //indexArray 중에서 filter에 맞는 것의 개수를 찾자.
    seed[seedLen] = filter;
    seed[seedLen + 1] = 0;
    int* idxArray = (int*)malloc(indexArrayLen * sizeof(int));
    int idxNum = 0;
    for (int k = 0; k < indexArrayLen; k++) {
        if (wordsLenArray[indexArray[k]] > seedLen) {
            if (filter == pWords[indexArray[k]][seedLen]) {
                idxArray[idxNum++] = indexArray[k];
            }
        }
    }
    if(idxNum > 0)
        searchWord2(seed, seedLen + 1, idxArray, idxNum, row + 1, col);
    free(idxArray);
}

// 좌 
if (col - 1 >= 0 && trace[row][col - 1] != 1) {
    char filter = pBoard[row][col -1];
    //indexArray 중에서 filter에 맞는 것의 개수를 찾자.
    seed[seedLen] = filter;
    seed[seedLen + 1] = 0;
    int* idxArray = (int*)malloc(indexArrayLen * sizeof(int));
    int idxNum = 0;
    for (int k = 0; k < indexArrayLen; k++) {
        if (wordsLenArray[indexArray[k]] > seedLen) {
            if (filter == pWords[indexArray[k]][seedLen]) {
                idxArray[idxNum++] = indexArray[k];
            }
        }
    }
    if (idxNum > 0)
        searchWord2(seed, seedLen + 1, idxArray, idxNum, row, col -1);
    free(idxArray);
}

//우  
if (col + 1 < W && trace[row][col + 1] != 1) {
    char filter = pBoard[row][col+1];
    //indexArray 중에서 filter에 맞는 것의 개수를 찾자.
    seed[seedLen] = filter;
    seed[seedLen + 1] = 0;
    int* idxArray = (int*)malloc(indexArrayLen * sizeof(int));
    int idxNum = 0;
    for (int k = 0; k < indexArrayLen; k++) {
        if (wordsLenArray[indexArray[k]] > seedLen) {
            if (filter == pWords[indexArray[k]][seedLen]) {
                idxArray[idxNum++] = indexArray[k];
            }
        }
    }
    if (idxNum > 0)
        searchWord2(seed, seedLen + 1, idxArray, idxNum, row, col +1);
    free(idxArray);
}

trace[row][col] = 0;
                        


                        Solution in C++ :

class Solution
{
	public:
		bool dfs(int ind, int indi, int indj, vector<vector < char>> &board, string &search, int &row, int &col)
		{
			if (ind == search.size())
				return true;

			if (indi >= 0 and indi < row and indj >= 0 and indj < col)
			{
				if (board[indi][indj] != search[ind])
					return false;
					
				char originalchar = board[indi][indj];
				board[indi][indj] = '$';
				
				bool ans = dfs(ind + 1, indi + 1, indj, board, search, row, col) ||
					dfs(ind + 1, indi - 1, indj, board, search, row, col) ||
					dfs(ind + 1, indi, indj + 1, board, search, row, col) ||
					dfs(ind + 1, indi, indj - 1, board, search, row, col);

				board[indi][indj] = originalchar;

				return ans;
			}
			else
				return false;
		}

	vector<string> findWords(vector<vector < char>> &board, vector< string > &words)
	{
		int row = board.size();
		int col = board[0].size();

		vector<string> ans;
		vector<vector<pair<int, int>>> vp(27);
		for (int i = 0; i < row; i++)
		{
			for (int j = 0; j < col; j++)
				vp[board[i][j] - 'a'].push_back({ i, j });
		}

		int starta = 0;
		int enda = 0;

		for (auto ele: words)
		{
			if (ele[0] == 'a')
				starta++;
				
			if (ele[ele.size() - 1] == 'a')
				enda++;
		}

		bool reversehaikya = false;
		if (starta > enda)
		{
			reversehaikya = true;
			for (int i = 0; i < words.size(); i++)
				reverse(words[i].begin(), words[i].end());
		}

		for (auto search: words)
		{
			bool flag = false;

			for (auto ele: vp[search[0] - 'a'])
			{
				flag = dfs(0, ele.first, ele.second, board, search, row, col);
                
				if (flag)
				{
					if (reversehaikya)
						reverse(search.begin(), search.end());

					ans.push_back(search);
					break;
				}
			}
		}
		return ans;
	}
};
                    


                        Solution in Java :

class Solution {
    public boolean dfs(int ind , int indi , int indj , char[][] board , String search , int row , int col){
        if(ind == search.length()){
            return true;
        }
        if(indi >= 0 && indi < row && indj>=0 && indj<col){
            if(board[indi][indj] != search.charAt(ind)){
                return false;
            }
            char originalchar = board[indi][indj];
            board[indi][indj] = '$';
            boolean ans = dfs(ind+1 , indi+1  , indj , board , search , row , col) ||
            dfs(ind+1 , indi-1  , indj , board , search , row , col) ||
            dfs(ind+1 , indi  , indj+1 , board , search , row , col) ||
            dfs(ind+1 , indi  , indj-1 , board , search , row , col);

            board[indi][indj] = originalchar;
            return ans;
        }
        else
            return false;
    }
    public List<String> findWords(char[][] board, String[] words) {
        int row = board.length;
        int col = board[0].length;
        List<String> ans = new ArrayList<>();
        List<List<Pair<Integer , Integer>>> v = new ArrayList<>();
        for(int i=0 ; i<26 ; i++){
            v.add(new ArrayList<>());
        }
        for(int i=0 ; i<row ; i++){
            for(int j=0; j<col ; j++){
                v.get(board[i][j] - 'a').add(new Pair<>(i , j));
            }
        }
        int start = 0 , end = 0;
        
            for(String word : words){
                if(word.charAt(0) == 'a')
                    start++;
                if(word.charAt(word.length()-1) == 'a')
                    end++;     
            }
            boolean reversehaikya = false;
            if(start > end){
                for(int i=0 ; i<words.length; i++){
                    reversehaikya = true;
                    words[i] = new StringBuilder(words[i]).reverse().toString();
                }
            }
        for(String search : words){
            boolean flag = false;
            for(Pair<Integer , Integer> ele : v.get(search.charAt(0) - 'a')){
                flag = dfs(0 , ele.getKey() , ele.getValue() , board , search , row , col);
                if(flag){
                    if(reversehaikya)
                        search = new StringBuilder(search).reverse().toString();
                        ans.add(search);
                       break;
                }
            }
        }
        return ans;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        m = len(board)
        n = len(board[0])
        res = []

        d = [[0, 1], [0, -1], [1, 0], [-1, 0]]

        ref = set()
        for i in range(m):
            for j in range(n-1):
                ref.add(board[i][j] + board[i][j+1])
        for j in range(n):
            for i in range(m-1):
                ref.add(board[i][j] + board[i+1][j])

        for word in words:
            f = True
            for i in range(len(word)-1):
                if word[i:i+2] not in ref and word[i+1] + word[i] not in ref:
                    f = False
                    break
            if not f:
                continue
            if self.findWord(word, m, n, board, d):
                res.append(word)
        return res
    
    def findWord(self, word, m, n, board, d) -> bool:
        if word[:4] == word[0] * 4:
            word = ''.join([c for c in reversed(word)])
        starts = []
        stack = []
        visited = set()
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    if len(word) == 1:
                        return True
                    starts.append((i, j))
        for start in starts:
            stack.append(start)
            visited.add((start, ))
            l = 1
            while stack != [] and l < len(word):
                x, y = stack[-1]
                for dxy in d:
                    nx, ny = x + dxy[0], y + dxy[1]
                    if 0 <= nx < m and 0 <= ny < n:
                        if board[nx][ny] == word[l]:
                            if (nx, ny) not in stack and tuple(stack) + ((nx, ny),) not in visited:
                                stack.append((nx, ny))
                                visited.add(tuple(stack))
                                l += 1
                                if l == len(word):
                                    return True
                                break
                else:
                    stack.pop()
                    l -= 1
        else:
            return False
                    


View More Similar Problems

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →