Crossword Puzzle


Problem Statement :


A 10 x 10  Crossword grid is provided to you, along with a set of words (or names of places) which need to be filled into the grid. Cells are marked either + or -. Cells marked with a - are to be filled with the word list.

The following shows an example crossword from the input crossword grid and the list of words to fit,



Function Description

Complete the crosswordPuzzle function in the editor below. It should return an array of strings, each representing a row of the finished puzzle.

crosswordPuzzle has the following parameter(s):

crossword: an array of 10 strings of length 10 representing the empty grid
words: a string consisting of semicolon delimited strings to fit into crossword.

 
Input Format

Each of the first 10 lines represents crossword[ i ], each of which has 10 characters, crossword[ i ][ j ].

The last line contains a string consisting of semicolon delimited word[ i ]  to fit.


Output Format

Position the words appropriately in the 10 x 10  grid, then return your array of strings for printing.



Solution :



title-img


                            Solution in C :

In   C++ :




#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std; 

const int GRID_SIZE = 10; 

typedef struct {
	int x; 
	int y; 
	bool isHoriz; 
	int len; 
} placement; 
bool sortLongestFirst(const placement& left, const placement& right){
	if (left.len != right.len) return left.len > right.len; 
	if (left.x != right.x) return left.x < right.x; 
	return left.y < right.y; 
}

bool longfirst(const string& left, const string& right){
	return left.length() > right.length(); 
}

bool solve(const vector<vector<char> >& grid, 
	const vector<placement>& spots, 
	const vector<string>& words){

	if (words.empty() && spots.empty()){
		for(int i=0; i<GRID_SIZE; i++){
			for(int j=0; j<GRID_SIZE; j++){
				cout << grid[i][j]; 
			}
			cout << endl; 
		}
		return true; 
	}
	if (words.empty() || spots.empty()) return false; 
	if (words[0].length() != spots[0].len) return false; 
	vector<placement> spots2(spots.begin()+1, spots.end()); 
	vector<string> words2; 
	for(int i=0; i<words.size(); i++){
		const string& w = words[i]; 
		vector<vector<char> > g2 = grid; 
		int x = spots[0].x; 
		int y = spots[0].y; 
		bool valid = true; 
		for(int l = 0; l<spots[0].len; l++){
			if (g2[x][y]=='-' || g2[x][y]==w[l]){
				g2[x][y] = w[l]; 
			} else {
				valid = false; 
				break; 
			}
			if (spots[0].isHoriz) y++; 
			else x++; 
		}
		if (!valid) continue; 

		words2.clear(); 
		for(int i2=0; i2<i; i2++)              words2.push_back(words[i2]); 
		for(int i2=i+1; i2<words.size(); i2++) words2.push_back(words[i2]); 
		if (solve(g2, spots2, words2)) return true; 
	}
	return false; 
}

int main(void){
	vector<vector<char> > grid(GRID_SIZE, vector<char>(GRID_SIZE)); 
	for(int i=0; i<GRID_SIZE; i++){
		string line; 
		cin >> line; 
		for(int j=0; j<GRID_SIZE; j++){
			grid[i][j] = line[j]; 
		}
	}
	string wordline; 
	cin >> wordline; 
	vector<string> words; 
	wordline+=";"; 
	istringstream iss(wordline); 
	string item; 
	while(getline(iss, item, ';')) words.push_back(item); 

	vector<placement> spots; 
	placement empty_spot; 
	for(int i=0; i<GRID_SIZE; i++){
		int gap_start = -1; 
		int gap_len = -1; 
		for(int j=0; j<GRID_SIZE; j++){
			if (grid[i][j]=='-'){
				if (gap_start>=0) gap_len++; 
				else {
					gap_start = j; 
					gap_len = 1; 
				}
			} else {
				if (gap_len>1){
					empty_spot.x = i; 
					empty_spot.y = gap_start; 
					empty_spot.isHoriz = true; 
					empty_spot.len = gap_len; 
					spots.push_back(empty_spot); 
				}
				gap_start = -1; 
				gap_len = -1; 
			}
		}
		if (gap_len>1){
			empty_spot.x = i; 
			empty_spot.y = gap_start; 
			empty_spot.isHoriz = true; 
			empty_spot.len = gap_len; 
			spots.push_back(empty_spot); 
		}
	}
	for(int j=0; j<GRID_SIZE; j++){
		int gap_start = -1; 
		int gap_len = -1; 
		for(int i=0; i<GRID_SIZE; i++){
			if (grid[i][j]=='-'){
				if (gap_start>=0) gap_len++; 
				else {
					gap_start = i; 
					gap_len = 1; 
				}
			} else {
				if (gap_len>1){
					empty_spot.x = gap_start; 
					empty_spot.y = j; 
					empty_spot.isHoriz = false; 
					empty_spot.len = gap_len; 
					spots.push_back(empty_spot); 
				}
				gap_start = -1; 
				gap_len = -1; 
			}
		}
		if (gap_len>1){
			empty_spot.x = gap_start; 
			empty_spot.y = j; 
			empty_spot.isHoriz = false; 
			empty_spot.len = gap_len; 
			spots.push_back(empty_spot); 
		}
	}
	sort(spots.begin(), spots.end(), sortLongestFirst); 
	sort(words.begin(), words.end(), longfirst); 
	solve(grid, spots, words); 
	return 0; 
}








In   Java  :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    
    class Point {
        boolean isVertical;
        int length;
        int x;
        int y;
        Point(boolean v, int l, int i, int j) {
            isVertical = v;
            length = l;
            x = i;
            y = j;
        }
        public String toString() {
            return "v="+isVertical+",l="+length+",x="+x+",y="+y;
        }
    };
    
    public static boolean isBorder(char board[][], int i, int j) {
        if (i<0 || i >= 10)
            return true;
        if (j<0 || j >= 10)
            return true;
        char c = board[i][j];
        if(c == '+')
            return true;
        else return false;
    }
    
    public boolean canInsert(char board[][], Point p, String word, boolean insert) {
        if (p.length != word.length())
            return false;
        for(int i=0; i < word.length(); i++) {
            char c = word.charAt(i);
            int x = p.x;
            int y = p.y;
            if(p.isVertical)
                x = x+i;
            else
                y = y+i;
            if(board[x][y] != '-' && board[x][y] != c)
                return false;
            else {
                if(insert)
                    board[x][y] = c;
            }
        }
        return true;        
    }
    
    public void showBoard(char board[][]) {
        for (int i=0; i < 10; i++) {
            for (int j=0; j < 10; j++) {
                System.out.print(board[i][j]);
            }
            System.out.println();
        }
    }
    
    public char[][] copyBoard(char board[][]) {
        char[][] newBoard = new char[10][10];
        for(int i=0; i<10; i++) {
            for (int j=0; j<10; j++) {
                newBoard[i][j] = board[i][j];
            }
        }
        return newBoard;
    }
    
    
    public boolean solve(char board[][], LinkedList<Point> points, LinkedList<String> wordList) {

        // if no points, and no words then we are successful so print board
        if(points.size() == 0 && wordList.size() == 0) {
            showBoard(board);
            return true;
        }
        
        if(points.size() == 0 && wordList.size() > 0) {
            return false;
        }
        
        LinkedList<String> triedWords = new LinkedList<String>();        
        Point p = points.removeFirst();        
        Iterator<String> iter = wordList.iterator();
        while(iter.hasNext()) {
            String word = iter.next();             
            if(canInsert(board, p, word, false)) {
                char[][] newBoard = copyBoard(board);
                canInsert(newBoard, p, word, true);
                iter.remove();
                LinkedList<String> both = new LinkedList<String>();
                both.addAll(wordList);
                both.addAll(triedWords);
                boolean sts = solve(newBoard, points, both);
                if (sts)
                    return true;
                else {
                    //System.out.println("Reverse insert " + word + " at p" + p);
                    //showBoard(board);
                    triedWords.push(word); 
                }
            } else {
                //System.out.println("Fail insert " + word + " at p" + p);
            }
            
        }
        
        // no luck, add point back and return.
        points.addFirst(p);        
        return false;
    }

    
    public LinkedList<Point> getStarts(char board[][]) {
        LinkedList<Point> plist = new LinkedList<Point>();
        for(int i=0; i<10; i++) {
            for (int j=0; j<10; j++) {
                char c = board[i][j];
                if(c == '-') {
                    if(isBorder(board, i-1, j) && !isBorder(board, i+1, j)) {
                        int l=0;
                        while(!isBorder(board, i+l, j))
                            l++;
                        //System.out.println(l + " long vertical at " + i + "," + j);
                        Point p = new Point(true, l, i, j);
                        plist.add(p);
                    }
                    if(isBorder(board, i, j-1) && !isBorder(board, i, j+1)) {
                        int l=0;
                        while(!isBorder(board, i, j+l))
                            l++;
                        //System.out.println(l + " long horizontal at " + i + "," + j);
                        Point p = new Point(false, l, i, j);
                        plist.add(p);
                    }
                }
            }
        }
        return plist;
    }
    
    
    public void myMain(String[] args) {
 
        Scanner scanner = new Scanner(System.in);
        char board[][] = new char[10][10];
        for (int i=0; i < 10; i++) {
            String line = scanner.nextLine();
            for (int j=0; j < 10; j++) {
                board[i][j] = line.charAt(j);
            }
        }
        String wordLine = scanner.nextLine();
        String words[] = wordLine.split(";");
        
        LinkedList<String> wordList = new LinkedList<String>();
        for (int i=0; i < words.length; i++) {
            wordList.add(words[i]);
        }

        LinkedList<Point> starts = getStarts(board);
        solve(board, starts, wordList);    
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        s.myMain(args);
    }

}








In   C  :






#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
char C[10][11];

char words[100][100];
int Placed[100];
int nwords;




int CanPlace(int i,int j,int word)
{
     int len = strlen(words[word]);
   // printf("can Place..%d %d %s %d \n",i, j,words[word],len);
    if(Placed[word] ==1)
        return 0;
     int k=0;
  //  int len = strlen(words[word]);
    int horiz =1;
    int vert = 2;
    for(k=0;k<len;k++)
    { 
        if((C[i+k][j] != '-' && C[i+k][j] != words[word][k]))
            horiz =0;
           
        if((C[i][j+k] != '-' && C[i][j+k]!=words[word][k]))
            vert = 0;
    }
    
    return horiz+vert;   
    
}
void Place( int i,int j,int or,int word)
{
   // printf("Placing..%d %d %d %s\n",i,j,or,words[word]);
    int k=0;
    int len = strlen(words[word]);
    for(k=0;k<len;k++)
    {
        if(or == 1)
          C[i+k][j] = words[word][k];
        else
          C[i][j+k] = words[word][k];
    }
    Placed[word] = 1;
    /*for(i=0;i<10;i++)
        printf("%s\n",C[i]);
    for(i=0;i<nwords;i++)
        printf("%d ",Placed[i]);*/
  //  printf("\n");
}

void UnPlace( int i,int j,int or,int word)
{
    // printf("unPlacing..%d %d %s\n",i,j,words[word]);
    int k=0;
    int len = strlen(words[word]);
    for(k=0;k<len;k++)
    {
        if(or == 1)
          C[i+k][j] = '-';
        else
          C[i][j+k] = '-';
    }
    Placed[word] = 0;
      
}
    

void SolveCross(int i,int j)
{
    //printf("solve %d %d\n",i,j);
   
   if(i==10)
       return;
    
    
    int k;
     for(k=0;k<nwords;k++)
        if(Placed[k] == 0)
         break;
     if(k==nwords)
     {
         for(i=0;i<10;i++)
            printf("%s\n",C[i]);
         return;
     }
         
     
   if(C[i][j] != '+') //Empty
   {
       //Try all words here
      int o;
      for(k=0;k<nwords;k++)
      {
         if((o=CanPlace(i,j,k))!=0) // check for kth word starting with i,j
         {   
                Place(i,j,o,k);
                int nextj = j+1;
                int nexti = nextj==10?i+1:i;
                SolveCross(nexti,nextj%10);
                UnPlace(i,j,o,k);
            if(o==3)
             {  
                Place(i,j,1,k);
                int nextj = j+1;
                int nexti = nextj==10?i+1:i;
                SolveCross(nexti,nextj%10);
                UnPlace(i,j,1,k);
             }
         }
   }
       if(k==nwords)
           {
          // printf("could not place all\n");
            int nextj = j+1;
                int nexti = nextj==10?i+1:i;
                SolveCross(nexti,nextj%10);
       }
   }
   else{
                int nextj = j+1;
                int nexti = nextj==10?i+1:i;
                SolveCross(nexti,nextj%10);
   }
   
}





int main() {

    int i,k;
    for(i=0;i<10;i++)
        scanf("%s",C[i]);   
    getchar();
    i=0;
    while(scanf("%[^;];s",words[i])!=EOF)
        i++;
    nwords = i;
    memset(Placed,0,nwords*sizeof(int));    
    SolveCross(0,0);
    
     //for(i=0;i<10;i++)
       // printf("%s\n",C[i]);
    
    return 0;
}








In   Python3   :








def readInts(): return map(int, input().strip().split())

def make_sets(cs):
    rows = len(cs)
    cols = len(cs[0])
    out_sets = set()
    visited = set()
    for sr in range(rows):
        for sc in range(cols):            
            if cs[sr][sc] != "-": continue
            if sc==0 or cs[sr][sc-1] != "-":
                # right            
                c = sc
                while c < cols and cs[sr][c] == "-":
                    visited.add( (sr,c) )
                    c += 1
                if c-1 > sc: out_sets.add( ((sr,sc), c-sc, (0,1)) )
            if sr==0 or cs[sr-1][sc] != "-":
                # down
                r = sr
                while r < rows and cs[r][sc] == "-":
                    visited.add( (r,sc) )
                    r += 1
                if r-1 > sr: out_sets.add( ((sr,sc), r-sr, (1,0)) )
    return out_sets

def solve_sets(ss,ws,used):
    def addt(a,b):
        ar,ac = a
        br,bc = b
        return (ar+br,ac+bc)
    if not ws: return used
    w = ws.pop()
    for (src,size,dd) in ss:
        if len(w) != size: continue
        rc = src
        ok = True
        for d in range(size):
            if rc in used and used[rc]!=w[d]:
                ok = False
                break
            rc = addt(rc,dd)
        if not ok: continue
        used2 = dict(used)
        rc = src
        for d in range(size):
            used2[rc] = w[d]
            rc = addt(rc,dd)
        ss2 = set(ss)
        ss2.remove( (src,size,dd) )
        attempt = solve_sets(ss2,ws,used2)
        if attempt: return attempt
    ws.append(w)
    return None

cs = [ input().strip() for _ in range(10) ]
ws = input().strip().split(";")
ss = make_sets(cs)
sol = solve_sets(ss,ws,dict())
rows = len(cs)
cols = len(cs[0])

for r in range(rows):
    a = []
    for c in range(cols):
        if (r,c) in sol: a.append(sol[ (r,c) ])
        else: a.append(cs[r][c])
    print("".join(a))
                        








View More Similar Problems

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 →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →