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 <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;
}







))
                        


                        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; 
}
                    


                        Solution in Java :

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);
    }

}
                    


                        Solution in Python : 
                            
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 and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

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 →