0% found this document useful (0 votes)
10 views

DS File

Uploaded by

Raman Bajaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DS File

Uploaded by

Raman Bajaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

BHARATI VIDYAPEETH COLLEGE OF ENGINEERING

NEW DELHI

Data Structures
Session: 2023 – 27

PROJECT-BASED LEARNING
Crossword Puzzle Using Matrix

Submitted To: Submitted By:


Dr. Surender Kaur Raman Bajaj
Prof. (Data Structures) IT – 1 (Sem 3)
01311503123
SOURCE CODE

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

const int N = 10;

void printCrossword(const vector<vector<char>>& grid) {


for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cout << grid[i][j] << " ";
}
cout << endl;
}
}

bool canPlaceHorizontally(const vector<vector<char>>& grid, const


string& word, int row, int col) {
if (col + word.length() > N) return false;

for (int i = 0; i < word.length(); ++i) {


if (grid[row][col + i] != '-' && grid[row][col + i] != word[i]) {
return false;
}
}

return true;
}

bool canPlaceVertically(const vector<vector<char>>& grid, const


string& word, int row, int col) {
if (row + word.length() > N) return false;

for (int i = 0; i < word.length(); ++i) {


if (grid[row + i][col] != '-' && grid[row + i][col] != word[i]) {
return false;
}
}

return true;
}
void placeHorizontally(vector<vector<char>>& grid, const string& word,
int row, int col) {
for (int i = 0; i < word.length(); ++i) {
grid[row][col + i] = word[i];
}
}

void placeVertically(vector<vector<char>>& grid, const string& word,


int row, int col) {
for (int i = 0; i < word.length(); ++i) {
grid[row + i][col] = word[i];
}
}

bool placeWord(vector<vector<char>>& grid, const string& word) {


int attempts = 0;
bool placed = false;

while (attempts < 100 && !placed) {


int row = rand() % N;
int col = rand() % N;
bool horizontal = rand() % 2;

if (horizontal) {
if (canPlaceHorizontally(grid, word, row, col)) {
placeHorizontally(grid, word, row, col);
placed = true;
}
} else {
if (canPlaceVertically(grid, word, row, col)) {
placeVertically(grid, word, row, col);
placed = true;
}
}

attempts++;
}

return placed;
}

int main() {
srand(time(0));

vector<string> words = {"HELLO", "WORLD", "CROSSWORD",


"PUZZLE", "CODE", "MATRIX", "RANDOM"};

vector<vector<char>> grid(N, vector<char>(N, '-'));


for (const string& word : words) {
bool success = placeWord(grid, word);
if (!success) {
cout << "Failed to place word: " << word << endl;
}
}

printCrossword(grid);

return 0;
}
OUTPUT

You might also like