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

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →