You are on page 1of 7

Las Vegas Algorithms: The Eight

Queen problem
Gajera Niraj Borsaniya Parth
MCA Department MCA Department
Nirma University Nirma University
Ahmedabad, India Ahmedabad, India
23MCA016@nirmauni.ac.in 23MCA004@nirmauni.ac.in

Abstract—This paper presents a novel application of the Las


Vegas approach to solve the classical 8-queens problem. The 8-
queens problem involves placing eight queens on an 8x8
chessboard in such a way that no two queens threaten each
other. The Las Vegas algorithm, known for its randomized
nature with a guaranteed correctness of solutions, is applied to
tackle this combinatorial optimization problem. This paper
explores the implementation, performance analysis, and
comparison with deterministic methods.

I. INTRODUCTION
The 8-queens problem is a well-known problem in
computer science and combinatorial optimization. The
objective is to find all possible arrangements of eight
queens on an 8x8 chessboard where no two queens can
attack each other. Traditional deterministic algorithms
such as backtracking are commonly used for solving this
problem. However, this paper explores the application
of the Las Vegas approach, which introduces
randomness into the solution process. IV. USING THE LAST VEGAS ALGORITHM
Las Vegas algorithm is a randomized algorithm that
II. EASE OF USE always gives correct results; that is, . However, the
runtime of a Las Vegas algorithm differs depending on
The Las Vegas algorithm for the 8-queens problem the input. The usual definition of a Las Vegas algorithm
involves randomly placing queens on the chessboard includes the restriction that the expected runtime be
and checking whether each placement satisfies the finite, where the expectation is carried out over the
constraint of no two queens attacking each other. If a space of random information, or entropy, used in the
valid solution is found, it is returned; otherwise, the algorithm. An alternative definition requires that a Las
process is repeated with a different random placement. Vegas algorithm always terminates (is effective), but
The algorithm continues until a valid solution is found. may output a symbol not part of the solution space to
indicate failure in finding a solution. The nature of Las
Vegas algorithms makes them suitable in situations
III. PROBLEM STATEMENT
where the number of possible solutions is limited, and
The eight queens’ problem is a classical combinatorial where verifying the correctness of a candidate solution
problem. To access to right solution of this problem, we is relatively easy while finding a solution is complex.
must put all the queens on the 8x8 board so that no
queen is attacked with the other queens (No Queen
conflicting with other queens).
So, the solution must be nonattack (the queen is attacked
if it shares the same row, column, or diagonal with
another queen) as shown in "Figure 1" [1,2,3]. In the
other words, a solution of the eight queens’ problem
must be ensured that each queen can move to the eight
neighboring directions (two vertical, two horizontal and
four diagonal directions) without attacking with other
queens as shown in figure.

XXX-X-XXXX-XXXX-X/XX/$XX.00 ©20XX IEEE


VI. USE CASES
V. CODE OF 8 QUEEN A. Machine Learning and Optimization: Randomized
algorithms are utilized in various machine learning
import random
tasks such as optimization, clustering, and
dimensionality reduction. They are often employed to
def printBoard(board, n):
handle large datasets efficiently and to explore diverse
for i in range(n):
for j in range(n): solutions.
print(board[i][j], end=" ")
print("\n")
print("\n")
B. Network Routing and Optimization: In network routing
def QueensLasVegas(n):
board = [[0 for j in range(n)] for i in range(n)]
problems, randomized algorithms can be used to find
availColumns = [] efficient routes through a network, minimizing latency
for a in range(n): and congestion. They are applied in dynamic routing
availColumns.append(a)
R = 0
scenarios where network conditions change over time.
while len(availColumns) != 0 and R < n:
temp = []
for i in availColumns:
if isSafe(board, R, i): C. Cryptography and Security: Randomized algorithms
temp.append(i) play a crucial role in cryptography for generating
if len(temp) == 0:
return False secure cryptographic keys, performing encryption and
rand = random.choice(temp) decryption operations, and ensuring randomness in
board[R][rand] = 1
R += 1
cryptographic protocols. They are also employed in
availColumns.remove(rand) security protocols for authentication and access control.
printBoard(board, n)
return 1

def isSafe(board, row, col): D. Bioinformatics: Randomized algorithms are used in


for i in range(col):
if board[row][i]:
bioinformatics for analyzing biological data, such as
return False DNA sequencing and protein structure prediction. They
i = row
help in solving complex computational problems in
j = col
while i >= 0 and j >= 0: genomics, proteomics, and evolutionary biology.
if board[i][j]:
return False
i -= 1
j -= 1 E. Quantum Computing: Randomized algorithms have
i = row
applications in quantum computing for tasks such as
j = col
while i >= 0 and j < 8: quantum state preparation, quantum sampling, and
if board[i][j]: quantum optimization. They are utilized to exploit the
return False
i = i - 1
unique properties of quantum systems to solve
j = j + 1 computational problems more efficiently.
return True

i = 0
for a in range(1000): F. Game Theory and Economics: Randomized algorithms
if QueensLasVegas(8) == 1:
i += 1
are applied in game theory and economics for modeling
print(i) strategic interactions, equilibrium analysis, and
print("Success rate is: ", i/1000)
mechanism design. They are used to study the behavior
of agents in complex systems and to design incentive
mechanisms for achieving desirable outcomes.

G. Distributed Systems: Randomized algorithms are


employed in distributed systems for achieving consensus,
leader election, and load balancing. They help in
designing fault-tolerant and scalable distributed
protocols that can operate efficiently in dynamic
environments

Quantum Computing
This use case highlights how quantum computing, combined rows/columns of a chessboard and colors to the
with the Las Vegas algorithm approach, can tackle the N- presence/absence of queens.
Queens problem efficiently, offering benefits in terms of Scheduling and Timetabling:
Quantum computing can optimize scheduling and
speed, scalability, and solution quality.
timetabling problems by efficiently assigning tasks or events
to time slots or resources. The N-Queens algorithm can be
Quantum Computing Approach: used to find conflict-free schedules by mapping tasks to
queens and time slots/resources to positions on a
Quantum computing harnesses the principles of quantum chessboard.
mechanics to perform computations. Unlike classical DNA Sequence Analysis:
computers that use bits to represent information as either 0 Quantum computing can aid in DNA sequence analysis,
or 1, quantum computers use quantum bits or qubits, which particularly in solving alignment and matching problems.
can exist in superpositions of states, enabling them to The N-Queens algorithm can be adapted to find optimal
process vast amounts of data simultaneously. alignments between DNA sequences by representing
nucleotides as chessboard positions and exploring possible
Problem Representation: matches using quantum parallelism.
Telecommunications Network Optimization:
Quantum computing represents the N-Queens problem using Quantum computing can optimize telecommunications
qubits, the fundamental units of quantum information. Each network layouts and routing configurations to minimize
qubit encodes a potential position for a queen on the interference and maximize efficiency. The N-Queens
chessboard. algorithm can be utilized to find optimal network
configurations by representing network nodes and
Quantum Gates and Operations: connections as queens and exploring interference-free
placements using quantum principles.
Quantum gates manipulate qubits to explore possible Resource Allocation in Logistics:
solutions. These gates perform operations such as Quantum computing can optimize resource allocation
superposition, entanglement, and interference, allowing for problems in logistics and supply chain management, such as
the simultaneous evaluation of multiple board warehouse layout design and vehicle routing. The N-Queens
configurations. algorithm can assist in finding optimal resource allocations
by representing resources and constraints as queens and
Superposition and Parallelism: exploring feasible configurations using quantum parallelism.
Cryptographic Key Generation:
Quantum superposition enables qubits to exist in multiple Quantum computing can enhance cryptographic key
states simultaneously. This property allows the quantum generation by efficiently generating secure key pairs. The N-
algorithm to explore many potential solutions in parallel, Queens algorithm can be applied to generate prime numbers
significantly speeding up the search process compared to or unique sequences by representing potential key values as
classical methods. queens and exploring valid combinations using quantum
superposition and measurement techniques.
Measurement and Verification:
Robot Path Planning:
After exploration, the quantum algorithm measures the Quantum computing can optimize robot path planning in
qubits to obtain a solution. Due to the probabilistic nature of complex environments by finding collision-free paths for
quantum computation, multiple measurements may be robots to navigate. The N-Queens algorithm can be adapted
necessary to ensure the correctness of the solution. to represent robot positions and obstacles as queens on a
Las Vegas Algorithm Approach: virtual chessboard, enabling the exploration of safe paths
The Las Vegas algorithm approach is utilized within the using quantum parallelism.
quantum framework to iteratively refine solutions. Random Financial Portfolio Optimization:
placements of queens are made on the chessboard, and Quantum computing can optimize financial portfolio
validity checks are performed. If an invalid solution is management by efficiently selecting investment strategies
found, the process repeats until a valid solution is obtained. that maximize returns while minimizing risks. The N-
Performance Evaluation: Queens algorithm can assist in portfolio optimization by
The performance of the quantum N-Queens algorithm is representing investment options and constraints as queens
evaluated based on solution quality, computational resources and exploring optimal combinations using quantum
utilized, and runtime. Quantum algorithms may offer principles.
significant speedups and scalability advantages over Drug Discovery and Molecular Simulation:
classical approaches, especially for large problem sizes. Quantum computing can accelerate drug discovery and
molecular simulation by efficiently exploring chemical
Graph Coloring Problems: compound configurations and interactions. The N-Queens
Quantum computing can be employed to solve graph algorithm can be utilized to find optimal molecular
coloring problems, where the goal is to assign colors to structures by representing atoms and bonds as queens on a
vertices of a graph such that no adjacent vertices share the lattice and exploring possible configurations using quantum
same color. The N-Queens algorithm can be adapted to find parallelism.
solutions to graph coloring by mapping vertices to
Image Recognition and Pattern Matching:
Quantum computing can enhance image recognition and changing conditions and requirements, enabling responsive
pattern matching tasks by efficiently analyzing large decision-making processes.
datasets and identifying complex patterns. The N-Queens Improved Resource Utilization:
algorithm can aid in image recognition by representing pixel Quantum algorithms, such as the N-Queens algorithm, can
arrangements and features as queens on a chessboard and optimize resource allocation and utilization in diverse
exploring potential matches using quantum parallelism. applications, leading to more efficient use of computational
resources, storage, and bandwidth. This optimization can
result in cost savings and improved performance across
Benefits: various industries.
Robustness to Noise and Errors:
Speedup: Quantum error correction techniques can enhance the
Quantum computing offers the potential for significant robustness of quantum algorithms, including the N-Queens
speedup over classical algorithms, allowing for faster algorithm, against noise and errors inherent in quantum
solution discovery and optimization in various domains. hardware. This improves the reliability and stability of
Scalability: quantum computations, ensuring consistent and accurate
Quantum algorithms, including the N-Queens algorithm, can results even in noisy environments.
efficiently scale with problem size, enabling the exploration Cross-Domain Applications:
of larger solution spaces and complex problem instances. The N-Queens algorithm, implemented on a quantum
Parallelism: computer, can find applications across multiple domains,
Quantum parallelism allows for the simultaneous including finance, logistics, healthcare, cybersecurity, and
exploration of multiple solution candidates, enhancing the more. Its versatility and scalability make it adaptable to
efficiency of search and optimization algorithms. diverse problem sets, driving innovation and advancements
Solution Quality: across various sectors.
Quantum algorithms can yield high-quality solutions to Data Privacy and Security:
optimization and combinatorial problems, providing Quantum computing offers advancements in cryptography,
accurate and reliable outcomes for real-world applications. enabling the development of secure encryption and
Resource Efficiency: decryption protocols. The N-Queens algorithm can
Quantum computing can optimize resource allocation and contribute to cryptographic applications by generating and
utilization, leading to more efficient and cost-effective optimizing cryptographic keys, enhancing data privacy and
solutions in various domains, such as logistics, security in communication systems and digital transactions.
telecommunications, and finance. Cross-Platform Compatibility:
Innovation and Discovery: Quantum algorithms, including the N-Queens algorithm, can
Quantum computing opens up new possibilities for be implemented on various quantum computing platforms
innovation and discovery across scientific, technological, and architectures, fostering interoperability and accessibility
and across different hardware and software ecosystems. This
commercial domains, driving advancements in areas such as ensures that quantum solutions are adaptable and scalable
healthcare, materials science, and artificial intelligence. across diverse computational environments.
Enhanced Accuracy: Sustainable Computing Practices:
Quantum computing offers the potential for enhanced Quantum computing has the potential to promote
accuracy in solving optimization problems by leveraging sustainability in computing by reducing energy consumption
quantum coherence and interference effects. This can lead to and environmental impact. The N-Queens algorithm, when
more precise solutions compared to classical approaches, executed on quantum hardware, contributes to sustainable
especially for problems with complex constraints and computing practices by optimizing resource usage and
interactions. minimizing carbon footprints associated with traditional
Reduced Energy Consumption: computing methods.
Quantum algorithms, including the N-Queens algorithm,
have the potential to reduce energy consumption in
computational tasks due to their inherent parallelism and
optimization capabilities. This can result in lower In conclusion, the utilization of the N-Queens algorithm in
operational costs and environmental impact, particularly in quantum computing offers a multitude of benefits across
large-scale computing environments. diverse domains and applications. By leveraging quantum
Novel Solution Discoveries: principles such as superposition, parallelism, and
Quantum computing enables the exploration of novel interference, the N-Queens algorithm enables efficient
solution spaces and unconventional problem-solving optimization and solution discovery for complex
approaches that may not be feasible with classical combinatorial problems. From enhancing accuracy and
algorithms. The N-Queens algorithm, when executed on a reducing energy consumption to promoting sustainability
quantum computer, can unveil unexpected solutions and and data privacy, quantum-enabled N-Queens algorithm
insights that lead to breakthroughs in various domains. provides transformative capabilities that drive innovation
Real-Time Decision Making: and address real-world challenges.
Quantum computing facilitates real-time decision making by Bioinformatics
rapidly evaluating and updating solutions to dynamic and
time-sensitive problems. The N-Queens algorithm, coupled
with quantum parallelism, allows for quick adaptation to In bioinformatics, the N-Queens problem serves as a
metaphorical model for solving various computational
challenges related to the arrangement and interaction of researchers can explore possible RNA secondary structure
biological entities such as DNA sequences, proteins, or configurations, aiding in predicting functional RNA motifs,
molecular structures. Here's how the N-Queens algorithm such as riboswitches or microRNA binding sites.
can be applied in bioinformatics: Comparative Genomics and Genome
Rearrangement:
Genomic Sequence Analysis: Comparative genomics involves comparing genetic
The N-Queens problem can be used to represent the sequences across different species to understand
arrangement of nucleotides within a DNA sequence. Just as evolutionary relationships and identify conserved regions.
queens must be placed on a chessboard such that they do not Genome rearrangement events, such as inversions,
threaten each other, certain patterns of nucleotides may be translocations, and duplications, can be represented using
constrained due to genetic interactions or functional combinatorial optimization problems like the N-Queens
requirements. By adapting N-Queens algorithms, problem. By applying N-Queens algorithms, researchers can
bioinformaticians can explore possible configurations and model genome rearrangement scenarios, infer evolutionary
analyze the implications for gene expression, protein histories, and elucidate genomic rearrangement mechanisms
synthesis, or evolutionary relationships. driving species divergence and adaptation.
Protein Structure Prediction: Protein-Protein Interaction Networks:
In protein structure prediction, the N-Queens problem can Proteins interact with each other forming intricate networks
analogously represent the spatial arrangement of amino crucial for cellular functions. Analogous to the N-Queens
acids within a protein molecule. Certain amino acid residues problem, where queens represent interacting entities, such as
may need to be positioned in specific orientations to form proteins, protein-protein interaction networks can be
functional protein structures or to avoid steric clashes. By modeled using combinatorial optimization approaches. By
employing N-Queens algorithms, researchers can explore adapting N-Queens algorithms, researchers can explore
the conformational space of proteins, predicting their three- possible configurations of protein interactions within
dimensional structures and understanding their functional networks, identifying key protein hubs, functional modules,
properties. and disease-associated protein complexes.
Drug Design and Molecular Docking: Epigenetic Regulation and Chromatin Structure:
N-Queens algorithms can be utilized to model the spatial Epigenetic modifications, such as DNA methylation and
interactions between small molecule ligands and protein histone modifications, play vital roles in regulating gene
binding sites during drug design and molecular docking expression and chromatin structure. The N-Queens problem
studies. Just as queens on a chessboard must avoid can be used to model chromatin configurations where
threatening each other, small molecules must bind to protein nucleosomes are positioned along DNA strands without
targets in energetically favorable conformations. By interfering with each other. By applying N-Queens
applying N-Queens approaches, researchers can explore the algorithms, researchers can investigate chromatin folding
binding geometries of ligands within protein active sites, patterns, epigenetic marks distribution, and their impact on
facilitating the design of novel therapeutic agents with gene regulation and cellular differentiation.
improved potency and selectivity. Population Genetics and Genetic Diversity:
Metabolic Pathway Analysis: Population genetics studies genetic variation within and
The N-Queens problem can represent the spatial between populations. The N-Queens algorithm can be
arrangement of metabolites within biochemical pathways. adapted to model genetic diversity scenarios, where alleles
Similar to arranging queens on a chessboard, the positioning are distributed across populations without violating genetic
of metabolites within pathways may be subject to spatial constraints. By employing N-Queens algorithms, researchers
constraints or regulatory interactions. By adapting N-Queens can simulate population genetic processes, such as gene
algorithms, bioinformaticians can analyze metabolic flow, genetic drift, and natural selection, shedding light on
networks, identifying optimal configurations that maximize population history, demographic changes, and disease
pathway efficiency or minimize metabolic flux imbalance. susceptibility patterns.
Evolutionary Biology and Phylogenetics:
In evolutionary biology and phylogenetics, the N-Queens Overall, the N-Queens algorithm serves as a versatile tool in
problem can be employed to model the evolutionary bioinformatics, offering insights into the spatial
relationships between species or genetic sequences. Just as arrangement, interaction, and optimization of biological
queens on a chessboard must be positioned to avoid threats, entities across various scales, from nucleotide sequences to
genetic sequences may exhibit structural constraints or molecular structures to ecological systems. Its application
conservation patterns due to evolutionary pressures. By highlights the interdisciplinary nature of computational
applying N-Queens algorithms, researchers can reconstruct biology, bridging concepts from mathematics and computer
phylogenetic trees and infer ancestral relationships, science to address complex biological questions.
elucidating the evolutionary dynamics of biological systems.
Benefits:
RNA Secondary Structure Prediction:
RNA molecules fold into complex secondary structures
crucial for their function. Similar to the N-Queens problem, Computational Efficiency:
where queens should not threaten each other, RNA The N-Queens algorithm, with its combinatorial
secondary structures have base pairing rules where certain optimization approach, offers computational efficiency in
nucleotides form base pairs while others avoid pairing to solving complex biological problems. By leveraging
maintain stability. By adapting N-Queens algorithms, efficient algorithms and data structures inspired by the N-
Queens problem, bioinformaticians can analyze large-scale Translational Impact:
biological datasets with reduced computational resources The insights gained from applying the N-Queens algorithm
and runtime, enabling faster discovery and hypothesis in bioinformatics have translational implications for
testing. biomedical research and healthcare. By elucidating
Scalability: molecular mechanisms underlying diseases, identifying
Bioinformatics often deals with datasets of varying sizes, potential drug targets, and predicting therapeutic outcomes,
from individual genetic sequences to entire genomic bioinformatics approaches informed by the N-Queens
databases. The scalability of the N-Queens algorithm allows algorithm contribute to precision medicine, drug discovery,
it to handle increasing dataset sizes efficiently. Whether and personalized healthcare, ultimately improving patient
predicting protein structures, analyzing genomic sequences, outcomes and public health.
or simulating population genetics, the N-Queens algorithm Education and Training:
can adapt to the computational demands of diverse The use of the N-Queens algorithm in bioinformatics
bioinformatics applications, accommodating larger datasets provides educational and training opportunities for students
without sacrificing performance. and researchers. By implementing and analyzing N-Queens-
Problem Modeling and Abstraction: based algorithms in bioinformatics courses, workshops, and
The N-Queens algorithm provides a versatile framework for research projects, individuals gain valuable experience in
modeling and abstracting diverse biological problems. By algorithm development, computational biology, and
mapping biological entities and interactions onto the N- problem-solving skills, preparing them for careers in
Queens problem, researchers can formulate complex academia, industry, and healthcare.
biological questions as combinatorial optimization
problems, facilitating algorithm design and implementation.
This abstraction allows for a unified approach to tackling Overall, the benefits of using the N-Queens algorithm in
various bioinformatics challenges, from sequence analysis to bioinformatics extend beyond computational efficiency to
systems biology. encompass scalability, problem modeling, interdisciplinary
Interdisciplinary Insights: insights, algorithmic innovation, biological understanding,
The application of the N-Queens algorithm in bioinformatics translational impact, and educational value, positioning it as
fosters interdisciplinary collaboration between mathematics, a valuable tool for advancing biological research and
computer science, and biology. By bridging concepts from applications.
combinatorial optimization, algorithm design, and biological
modeling, the N-Queens algorithm enables researchers to
integrate diverse methodologies and perspectives, driving
innovation and cross-disciplinary advancements in ACKNOWLEDGMENT
understanding biological systems.
Algorithmic Innovation:
The adaptation of the N-Queens algorithm to bioinformatics
problems stimulates algorithmic innovation and algorithmic WE WOULD LIKE TO EXPRESS OUR SINCERE GRATITUDE TO
ALL THOSE WHO CONTRIBUTED TO THE COMPLETION OF THIS
diversity. Bioinformaticians can explore novel algorithmic
RESEARCH PAPER.
techniques inspired by the N-Queens problem, such as
heuristic search strategies, metaheuristic algorithms, and FIRST AND FOREMOST, WE EXTEND OUR DEEPEST
parallel computing approaches, to address specific APPRECIATION TO OUR FACULTY MEMBER PROF. SONIA
challenges in biological data analysis, optimization, and MITTAL WHOSE GUIDANCE, EXPERTISE, AND UNWAVERING
simulation. SUPPORT WERE INVALUABLE THROUGHOUT THIS RESEARCH
Insights into Biological Systems: ENDEAVOR. THEIR INSIGHTFUL FEEDBACK AND
The application of the N-Queens algorithm in bioinformatics CONSTRUCTIVE CRITICISM GREATLY ENRICHED THE QUALITY
yields insights into the organization, dynamics, and OF THIS WORK.
evolution of biological systems. By solving combinatorial
optimization problems analogous to biological phenomena, REFERENCES
researchers can uncover underlying principles governing [1] https://citeseerx.ist.psu.edu/document?
gene regulation, protein-protein interactions, evolutionary repid=rep1&type=pdf&doi=e63a015940646fd9bf428be61a2534b305
5d1766
dynamics, and ecosystem structure, enhancing our
[2] Wikipedia:- https://en.wikipedia.org/wiki/Las_Vegas_algorithm
understanding of complex biological processes and
[3] https://slideplayer.com/slide/4965867/
phenomena.

You might also like