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

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →