Skip to content
Snippets Groups Projects
Commit b31f60cc authored by Hikmat Farhat's avatar Hikmat Farhat
Browse files

added nqueens

parent 5bf5969d
No related branches found
No related tags found
No related merge requests found
/MinHeap.class
/MinHeapForGraphs.class
/Prim.class
/BfsGraph.class
/BfsVertex.class
......@@ -15,6 +15,8 @@ public class MinHeap {
// heap.insert(20);
// heap.insert(15);
// heap.insert(18);
for(int i=0;i<a.length;++i)
System.out.print(heap.deleteMin()+",");
System.out.println("Done");
}
public MinHeap() {
......
package minheap;
public class MinHeapForGraphs {
private int capacity;
private int size=0;
int[] keys;//used for min values that are usually updated during an algorithm
int [] v_indices;// corresponding vertex indices that DO NOT change
public static void main(String[] args) {
int[] a= {53,26,17,23,34,41,12,5,9};
MinHeap heap=new MinHeap(a);
//MinHeap heap=new MinHeap();
// heap.insert(30);
// heap.insert(25);
// heap.insert(20);
// heap.insert(15);
// heap.insert(18);
System.out.println("Done");
}
public MinHeapForGraphs() {
capacity=64;
keys=new int[capacity];
}
public MinHeapForGraphs(int capacity) {
this.capacity=capacity;
keys=new int[capacity];
}
public MinHeapForGraphs(int[] a) {
capacity=64;
keys=new int[capacity];
size=a.length;
for(int i=0;i<a.length;++i)
keys[i+1]=a[i];
for(int i=size/2;i>0;i--) {
percolateDown(i);
}
}
private void percolateUp(int hole) {
int tmp=keys[hole];
int v_idx=v_indices[hole];
while(hole/2>=1 && tmp<keys[hole/2]) {
keys[hole]=keys[hole/2];
v_indices[hole]=v_indices[hole/2];
hole=hole/2;
}
keys[hole]=tmp;
v_indices[hole]=v_idx;
}
public void insert(int val,int v_idx) {
//add code to check if the keys array is full
keys[++size]=val;
v_indices[size]=v_idx;
percolateUp(size);
}
private void percolateDown(int hole) {
int tmp=keys[hole];
int v_idx=v_indices[hole];//to keep track of vertex idx
int childIdx;
while(2*hole<=size) {
childIdx=2*hole;
if(childIdx<size && keys[childIdx]>keys[childIdx+1])childIdx++;
if(keys[childIdx]<tmp) {
keys[hole]=keys[childIdx];
v_indices[hole]=v_indices[childIdx];
hole=childIdx;
}
else break;
}
keys[hole]=tmp;
v_indices[hole]=v_idx;
}
public int deleteMin() {
int min=keys[1];
int min_idx=v_indices[1];
keys[1]=keys[size];
v_indices[1]=v_indices[size];
size--;
percolateDown(1);
return min;
}
}
package minheap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
/*Simple implementation of BFS traversal
*
*/
public class Prim {
public static void main(String[] args) {
BfsGraph g=new BfsGraph();
BfsVertex[] nodes=new BfsVertex[6];
for(int i=0;i<6;++i)
nodes[i]=new BfsVertex(Integer.toString(i));
/* The graph has 6 vertices with connections
* 0-1, 0-5,1-0,1-2,1-3,2-1,2-4,3-1,3-4,3-5
* 4-2,4-3,5-0,5-3
* Usually the connection are added from some
* description file but this will do.
*/
nodes[0].addAdj(nodes[1]);nodes[0].addAdj(nodes[5]);
nodes[1].addAdj(nodes[0]);nodes[1].addAdj(nodes[2]);
nodes[1].addAdj(nodes[3]);
nodes[2].addAdj(nodes[1]);nodes[2].addAdj(nodes[4]);
nodes[3].addAdj(nodes[1]);nodes[3].addAdj(nodes[4]);
nodes[3].addAdj(nodes[5]);
nodes[4].addAdj(nodes[2]);nodes[4].addAdj(nodes[3]);
nodes[5].addAdj(nodes[0]);nodes[5].addAdj(nodes[3]);
// add nodes to graph
for(int i=0;i<6;++i)
g.addVertex(nodes[i]);
bfs(g);
}
boolean possibleColour(BfsGraph g,int[] colours,int v_idx,int c) {
return true;
}
boolean kColor(BfsGraph g,int[] colours,int v_idx,int k) {
if(v_idx==colours.length)return true;
for(int c=1;c<=k;++c) {
if(possibleColour(g,colours,v_idx,c)) {
colours[v_idx]=c;
if(kColor(g,colours,v_idx+1,k))
return true;
colours[v_idx]=0;
}
}
return false;
}
static void bfs(BfsGraph g) {
Iterator<BfsVertex> itr=g.getVertices().iterator();
while(itr.hasNext()) {
BfsVertex v=itr.next();
if(!v.visited)
bfsVisit(v);
}
}
static void bfsVisit(BfsVertex source) {
Queue<BfsVertex> q=new LinkedList<BfsVertex>();
source.visited=true;
q.add(source);
while(!q.isEmpty()) {
BfsVertex u=q.remove();
System.out.print("node="+u.label+",d="+u.d
+",pred="+(u.p==null?"null":u.p.label)
);
System.out.println("");
Iterator<BfsVertex> itr=u.getAdj().iterator();
while(itr.hasNext()) {
BfsVertex v=itr.next();
if(!v.visited) {
v.p=u;
v.d=u.d+1;
v.visited=true;
q.add(v);
}
}
}
}
}
class BfsVertex{
boolean visited;
//predecessor
BfsVertex p;
int d=0;
String label;
LinkedList<BfsVertex> adj;
public BfsVertex(String label) {
this.label=label;
adj=new LinkedList<BfsVertex>();
}
void addAdj(BfsVertex v) {
adj.add(v);
}
LinkedList<BfsVertex> getAdj(){
return adj;
}
}
class BfsGraph{
int n;
LinkedList<BfsVertex> vertices;
public BfsGraph() {
n=0;
vertices=new LinkedList<BfsVertex>();
}
void addVertex(BfsVertex v) {
n++;
vertices.add(v);
}
LinkedList<BfsVertex> getVertices(){
return vertices;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>
/bin/
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>backtracking</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1647515962011</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=17
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=17
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=17
package backtracking;
import java.util.Arrays;
public class InterviewBit {
final int V = 4;
int[] color;
boolean isSafeToColor(int v, int[][] graphMatrix, int[] color, int c)
{
//check for each edge
for (int i = 0; i < V; i++)
if (graphMatrix[v][i] == 1 && c == color[i])
return false;
return true;
}
boolean graphColorUtil(int[][] graphMatrix, int m, int[] color, int v)
{
// If all vertices are assigned a color then return true
if (v == V)
return true;
// Try different colors for vertex V
for (int i = 1;i <= m; i++)
{
// check for assignment safety
if (isSafeToColor(v, graphMatrix, color, i))
{
color[v] =i;
// recursion for checking other vertices
if (graphColorUtil(graphMatrix, m, color, v + 1))
return true;
// if color doesnt lead to solution
color[v] = 0;
}
}
// If no color can be assigned to vertex
return false;
}
void printColoringSolution(int color[])
{
System.out.println("Color schema for vertices are: ");
for (int i = 0; i < V; i++)
System.out.println(color[i]);
}
/**
* It returns false if the m colors cannot be assigned
* otherwise return true and
* print color assignment result to all vertices.
*/
boolean graphColoring(int[][] graphMatrix, int m)
{
// Initialize all color values as 0.
color = new int[V];
Arrays.fill(color,0);
// Call graphColorUtil() for vertex 0
if (!graphColorUtil(graphMatrix, m, color, 0))
{
System.out.println(
"Color schema not possible");
return false;
}
// Print the color schema of vertices
printColoringSolution(color);
return true;
}
// Main driver program
public static void main(String args[])
{
InterviewBit interviewBit
= new InterviewBit();
int graphMatrix[][] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3; // Number of colors
interviewBit.graphColoring(graphMatrix, m);
}
}
\ No newline at end of file
package backtracking;
public class NQueens {
int n=4;
int[] Q=new int[n+1];
void backtrack(int row) {//found solution, print it
if (row==n+1) {
for(int i=1;i<n+1;++i)
System.out.print(Q[i]);
System.out.println("");
}
else {
for(int col=1;col<n+1;++col) {//try all possible columns
//note that even if a solution is found
//the algorithm will go on trying other
// configuration
boolean possible=true;
// j is the column under consideration
// test all the rows before r
// if any of them can attack queen at row r
// then j is no good
for(int i=1;i<row;++i) {//check previous rows
if( (Q[i]==col) || (Q[i]==col+row-i) || (Q[i]==col-row+i))
possible=false;
}
if (possible) {//possible choice
Q[row]=col;
//next row
backtrack(row+1);
}
//otherwise try the next possible j
}//end for
}//end else
}
public static void main(String[] args) {
NQueens nq=new NQueens();
nq.backtrack(1);
}
}
......@@ -14,4 +14,15 @@
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1647515962047</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
......@@ -34,6 +34,22 @@ public class Traversal {
bfs(g);
}
boolean possibleColour(BfsGraph g,int[] colours,int v_idx,int c) {
return true;
}
boolean kColor(BfsGraph g,int[] colours,int v_idx,int k) {
if(v_idx==colours.length)return true;
for(int c=1;c<=k;++c) {
if(possibleColour(g,colours,v_idx,c)) {
colours[v_idx]=c;
if(kColor(g,colours,v_idx+1,k))
return true;
colours[v_idx]=0;
}
}
return false;
}
static void bfs(BfsGraph g) {
Iterator<BfsVertex> itr=g.getVertices().iterator();
......
......@@ -14,4 +14,15 @@
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1647515962076</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
......@@ -14,4 +14,15 @@
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1647515962095</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
......@@ -39,8 +39,6 @@ static int bfsVisit(BfsVertex source,BfsVertex dest,int m) {
public static void main(String[] args){
// total number of nodes in the graph
int n = 8;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment