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

Array-DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3

View Solution →

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →