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 :
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
Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →