Created
February 22, 2024 18:35
-
-
Save alexjosesilva/567a5b329be871f50232f9bcf4776a1a to your computer and use it in GitHub Desktop.
Programação Lógica
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class OitoRainhas { | |
private static final int N = 8; // Tamanho do tabuleiro | |
public static void main(String[] args) { | |
int[][] tabuleiro = new int[N][N]; | |
if (resolverOitoRainhas(tabuleiro, 0)) { | |
imprimirTabuleiro(tabuleiro); | |
} else { | |
System.out.println("Não há solução para o problema das oito rainhas."); | |
} | |
} | |
// Método para resolver o problema das oito rainhas | |
private static boolean resolverOitoRainhas(int[][] tabuleiro, int coluna) { | |
if (coluna >= N) { | |
return true; // Todas as rainhas foram colocadas com sucesso | |
} | |
for (int linha = 0; linha < N; linha++) { | |
if (posicaoSegura(tabuleiro, linha, coluna)) { | |
tabuleiro[linha][coluna] = 1; // Coloca uma rainha na posição | |
if (resolverOitoRainhas(tabuleiro, coluna + 1)) { | |
return true; // Se a próxima rainha também for colocada com sucesso | |
} | |
// Se a próxima rainha não puder ser colocada, retrocede e tenta outra linha nesta coluna | |
tabuleiro[linha][coluna] = 0; | |
} | |
} | |
return false; // Não há posições seguras nesta coluna | |
} | |
// Método para verificar se uma posição é segura para colocar uma rainha | |
private static boolean posicaoSegura(int[][] tabuleiro, int linha, int coluna) { | |
// Verifica a linha | |
for (int i = 0; i < coluna; i++) { | |
if (tabuleiro[linha][i] == 1) { | |
return false; | |
} | |
} | |
// Verifica a diagonal superior esquerda | |
for (int i = linha, j = coluna; i >= 0 && j >= 0; i--, j--) { | |
if (tabuleiro[i][j] == 1) { | |
return false; | |
} | |
} | |
// Verifica a diagonal inferior esquerda | |
for (int i = linha, j = coluna; i < N && j >= 0; i++, j--) { | |
if (tabuleiro[i][j] == 1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
// Método para imprimir o tabuleiro | |
private static void imprimirTabuleiro(int[][] tabuleiro) { | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < N; j++) { | |
System.out.print(tabuleiro[i][j] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment