mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-21 11:10:08 +08:00
@ -1,4 +1,5 @@
|
||||
/** Author : Siddhant Swarup Mallick
|
||||
/**
|
||||
* Author : Siddhant Swarup Mallick
|
||||
* Github : https://github.com/siddhant2002
|
||||
*/
|
||||
|
||||
@ -15,13 +16,12 @@ public class AllPathsFromSourceToTarget {
|
||||
private int v;
|
||||
|
||||
// To store the paths from source to destination
|
||||
static List<List<Integer>> nm=new ArrayList<>();
|
||||
static List<List<Integer>> nm = new ArrayList<>();
|
||||
// adjacency list
|
||||
private ArrayList<Integer>[] adjList;
|
||||
|
||||
// Constructor
|
||||
public AllPathsFromSourceToTarget(int vertices)
|
||||
{
|
||||
public AllPathsFromSourceToTarget(int vertices) {
|
||||
|
||||
// initialise vertex count
|
||||
this.v = vertices;
|
||||
@ -31,8 +31,7 @@ public class AllPathsFromSourceToTarget {
|
||||
}
|
||||
|
||||
// utility method to initialise adjacency list
|
||||
private void initAdjList()
|
||||
{
|
||||
private void initAdjList() {
|
||||
adjList = new ArrayList[v];
|
||||
|
||||
for (int i = 0; i < v; i++) {
|
||||
@ -41,15 +40,12 @@ public class AllPathsFromSourceToTarget {
|
||||
}
|
||||
|
||||
// add edge from u to v
|
||||
public void addEdge(int u, int v)
|
||||
{
|
||||
public void addEdge(int u, int v) {
|
||||
// Add v to u's list.
|
||||
adjList[u].add(v);
|
||||
}
|
||||
|
||||
|
||||
public void storeAllPaths(int s, int d)
|
||||
{
|
||||
public void storeAllPaths(int s, int d) {
|
||||
boolean[] isVisited = new boolean[v];
|
||||
ArrayList<Integer> pathList = new ArrayList<>();
|
||||
|
||||
@ -61,9 +57,9 @@ public class AllPathsFromSourceToTarget {
|
||||
|
||||
// A recursive function to print all paths from 'u' to 'd'.
|
||||
// isVisited[] keeps track of vertices in current path.
|
||||
// localPathList<> stores actual vertices in the current path
|
||||
private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList)
|
||||
{
|
||||
// localPathList<> stores actual vertices in the current path
|
||||
private void storeAllPathsUtil(
|
||||
Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) {
|
||||
|
||||
if (u.equals(d)) {
|
||||
nm.add(new ArrayList<>(localPathList));
|
||||
@ -74,7 +70,7 @@ public class AllPathsFromSourceToTarget {
|
||||
isVisited[u] = true;
|
||||
|
||||
// Recursion for all the vertices adjacent to current vertex
|
||||
|
||||
|
||||
for (Integer i : adjList[u]) {
|
||||
if (!isVisited[i]) {
|
||||
// store current node in path[]
|
||||
@ -91,12 +87,11 @@ public class AllPathsFromSourceToTarget {
|
||||
}
|
||||
|
||||
// Driver program
|
||||
public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination)
|
||||
{
|
||||
public static List<List<Integer>> allPathsFromSourceToTarget(
|
||||
int vertices, int[][] a, int source, int destination) {
|
||||
// Create a sample graph
|
||||
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
|
||||
for(int i=0 ; i<a.length ; i++)
|
||||
{
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
g.addEdge(a[i][0], a[i][1]);
|
||||
// edges are added
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ public class ArrayCombination {
|
||||
length = k;
|
||||
Integer[] arr = new Integer[n];
|
||||
for (int i = 1; i <= n; i++) {
|
||||
arr[i-1] = i;
|
||||
arr[i - 1] = i;
|
||||
}
|
||||
return Combination.combination(arr, length);
|
||||
}
|
||||
|
@ -38,11 +38,7 @@ public class Combination {
|
||||
* @param <T> the type of elements in the array.
|
||||
*/
|
||||
private static <T> void backtracking(
|
||||
T[] arr,
|
||||
int index,
|
||||
TreeSet<T> currSet,
|
||||
List<TreeSet<T>> result
|
||||
) {
|
||||
T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
|
||||
if (index + length - currSet.size() > arr.length) return;
|
||||
if (length - 1 == currSet.size()) {
|
||||
for (int i = index; i < arr.length; i++) {
|
||||
|
@ -38,13 +38,7 @@ public class FloodFill {
|
||||
* @param newColor The new color which to be filled in the image
|
||||
* @param oldColor The old color which is to be replaced in the image
|
||||
*/
|
||||
public static void floodFill(
|
||||
int[][] image,
|
||||
int x,
|
||||
int y,
|
||||
int newColor,
|
||||
int oldColor
|
||||
) {
|
||||
public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) {
|
||||
if (x < 0 || x >= image.length) return;
|
||||
if (y < 0 || y >= image[x].length) return;
|
||||
if (getPixel(image, x, y) != oldColor) return;
|
||||
|
@ -4,9 +4,10 @@ import java.util.*;
|
||||
|
||||
/*
|
||||
* Problem Statement: -
|
||||
|
||||
Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of
|
||||
chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
|
||||
|
||||
Given a N*N board with the Knight placed on the first block of an empty board. Moving according
|
||||
to the rules of chess knight must visit each square exactly once. Print the order of each cell in
|
||||
which they are visited.
|
||||
|
||||
Example: -
|
||||
|
||||
@ -27,14 +28,14 @@ public class KnightsTour {
|
||||
|
||||
private static final int base = 12;
|
||||
private static final int[][] moves = {
|
||||
{ 1, -2 },
|
||||
{ 2, -1 },
|
||||
{ 2, 1 },
|
||||
{ 1, 2 },
|
||||
{ -1, 2 },
|
||||
{ -2, 1 },
|
||||
{ -2, -1 },
|
||||
{ -1, -2 },
|
||||
{1, -2},
|
||||
{2, -1},
|
||||
{2, 1},
|
||||
{1, 2},
|
||||
{-1, 2},
|
||||
{-2, 1},
|
||||
{-2, -1},
|
||||
{-1, -2},
|
||||
}; // Possible moves by knight on chess
|
||||
private static int[][] grid; // chess grid
|
||||
private static int total; // total squares in chess
|
||||
@ -75,23 +76,17 @@ public class KnightsTour {
|
||||
return false;
|
||||
}
|
||||
|
||||
Collections.sort(
|
||||
neighbor,
|
||||
new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
}
|
||||
Collections.sort(neighbor, new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
for (int[] nb : neighbor) {
|
||||
row = nb[0];
|
||||
column = nb[1];
|
||||
grid[row][column] = count;
|
||||
if (
|
||||
!orphanDetected(count, row, column) &&
|
||||
solve(row, column, count + 1)
|
||||
) {
|
||||
if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) {
|
||||
return true;
|
||||
}
|
||||
grid[row][column] = 0;
|
||||
@ -109,7 +104,7 @@ public class KnightsTour {
|
||||
int y = m[1];
|
||||
if (grid[row + y][column + x] == 0) {
|
||||
int num = countNeighbors(row + y, column + x);
|
||||
neighbour.add(new int[] { row + y, column + x, num });
|
||||
neighbour.add(new int[] {row + y, column + x, num});
|
||||
}
|
||||
}
|
||||
return neighbour;
|
||||
|
@ -51,9 +51,7 @@ public class MazeRecursion {
|
||||
setWay2(map2, 1, 1);
|
||||
|
||||
// Print out the new map1, with the ball footprint
|
||||
System.out.println(
|
||||
"After the ball goes through the map1,show the current map1 condition"
|
||||
);
|
||||
System.out.println("After the ball goes through the map1,show the current map1 condition");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map[i][j] + " ");
|
||||
@ -62,9 +60,7 @@ public class MazeRecursion {
|
||||
}
|
||||
|
||||
// Print out the new map2, with the ball footprint
|
||||
System.out.println(
|
||||
"After the ball goes through the map2,show the current map2 condition"
|
||||
);
|
||||
System.out.println("After the ball goes through the map2,show the current map2 condition");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map2[i][j] + " ");
|
||||
@ -85,7 +81,7 @@ public class MazeRecursion {
|
||||
* means the ball has gone through the path but this path is dead end
|
||||
* 5. We will need strategy for the ball to pass through the maze for example:
|
||||
* Down -> Right -> Up -> Left, if the path doesn't work, then backtrack
|
||||
*
|
||||
*
|
||||
* @author OngLipWei
|
||||
* @version Jun 23, 2021 11:36:14 AM
|
||||
* @param map The maze
|
||||
@ -99,7 +95,8 @@ public class MazeRecursion {
|
||||
}
|
||||
if (map[i][j] == 0) { // if the ball haven't gone through this point
|
||||
// then the ball follows the move strategy : down -> right -> up -> left
|
||||
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
|
||||
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
|
||||
// first。
|
||||
if (setWay(map, i + 1, j)) { // go down
|
||||
return true;
|
||||
} else if (setWay(map, i, j + 1)) { // go right
|
||||
@ -129,7 +126,8 @@ public class MazeRecursion {
|
||||
}
|
||||
if (map[i][j] == 0) { // if the ball haven't gone through this point
|
||||
// then the ball follows the move strategy : up->right->down->left
|
||||
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
|
||||
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
|
||||
// first。
|
||||
if (setWay2(map, i - 1, j)) { // go up
|
||||
return true;
|
||||
} else if (setWay2(map, i, j + 1)) { // go right
|
||||
|
@ -47,14 +47,8 @@ public class NQueens {
|
||||
List<List<String>> arrangements = new ArrayList<List<String>>();
|
||||
getSolution(queens, arrangements, new int[queens], 0);
|
||||
if (arrangements.isEmpty()) {
|
||||
System.out.println(
|
||||
"There is no way to place " +
|
||||
queens +
|
||||
" queens on board of size " +
|
||||
queens +
|
||||
"x" +
|
||||
queens
|
||||
);
|
||||
System.out.println("There is no way to place " + queens + " queens on board of size "
|
||||
+ queens + "x" + queens);
|
||||
} else {
|
||||
System.out.println("Arrangement for placing " + queens + " queens");
|
||||
}
|
||||
@ -73,11 +67,7 @@ public class NQueens {
|
||||
* @param columnIndex: This is the column in which queen is being placed
|
||||
*/
|
||||
private static void getSolution(
|
||||
int boardSize,
|
||||
List<List<String>> solutions,
|
||||
int[] columns,
|
||||
int columnIndex
|
||||
) {
|
||||
int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) {
|
||||
if (columnIndex == boardSize) {
|
||||
// this means that all queens have been placed
|
||||
List<String> sol = new ArrayList<String>();
|
||||
@ -96,7 +86,8 @@ public class NQueens {
|
||||
for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) {
|
||||
columns[columnIndex] = rowIndex;
|
||||
if (isPlacedCorrectly(columns, rowIndex, columnIndex)) {
|
||||
// If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column
|
||||
// If queen is placed successfully at rowIndex in column=columnIndex then try
|
||||
// placing queen in next column
|
||||
getSolution(boardSize, solutions, columns, columnIndex + 1);
|
||||
}
|
||||
}
|
||||
@ -111,11 +102,7 @@ public class NQueens {
|
||||
* @param columnIndex: column in which queen is being placed
|
||||
* @return true: if queen can be placed safely false: otherwise
|
||||
*/
|
||||
private static boolean isPlacedCorrectly(
|
||||
int[] columns,
|
||||
int rowIndex,
|
||||
int columnIndex
|
||||
) {
|
||||
private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) {
|
||||
for (int i = 0; i < columnIndex; i++) {
|
||||
int diff = Math.abs(columns[i] - rowIndex);
|
||||
if (diff == 0 || columnIndex - i == diff) {
|
||||
|
@ -1,11 +1,10 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
|
||||
/*
|
||||
* Problem Statement :
|
||||
* Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers.
|
||||
* For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3.
|
||||
* Therefore output will be 1.
|
||||
* Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers
|
||||
* of unique, natural numbers. For example, if N=100 and X=3, we have to find all combinations of
|
||||
* unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. Therefore output will be 1.
|
||||
*/
|
||||
public class PowerSum {
|
||||
|
||||
@ -16,26 +15,29 @@ public class PowerSum {
|
||||
return count;
|
||||
}
|
||||
|
||||
//here i is the natural number which will be raised by X and added in sum.
|
||||
// here i is the natural number which will be raised by X and added in sum.
|
||||
public void Sum(int N, int X, int i) {
|
||||
//if sum is equal to N that is one of our answer and count is increased.
|
||||
// if sum is equal to N that is one of our answer and count is increased.
|
||||
if (sum == N) {
|
||||
count++;
|
||||
return;
|
||||
} //we will be adding next natural number raised to X only if on adding it in sum the result is less than N.
|
||||
} // we will be adding next natural number raised to X only if on adding it in sum the
|
||||
// result is less than N.
|
||||
else if (sum + power(i, X) <= N) {
|
||||
sum += power(i, X);
|
||||
Sum(N, X, i + 1);
|
||||
//backtracking and removing the number added last since no possible combination is there with it.
|
||||
// backtracking and removing the number added last since no possible combination is
|
||||
// there with it.
|
||||
sum -= power(i, X);
|
||||
}
|
||||
if (power(i, X) < N) {
|
||||
//calling the sum function with next natural number after backtracking if when it is raised to X is still less than X.
|
||||
// calling the sum function with next natural number after backtracking if when it is
|
||||
// raised to X is still less than X.
|
||||
Sum(N, X, i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
//creating a separate power function so that it can be used again and again when required.
|
||||
// creating a separate power function so that it can be used again and again when required.
|
||||
private int power(int a, int b) {
|
||||
return (int) Math.pow(a, b);
|
||||
}
|
||||
|
@ -1,13 +1,12 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
|
||||
/*
|
||||
Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
|
||||
|
||||
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
|
||||
|
||||
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or
|
||||
vertically neighboring. The same letter cell may not be used more than once.
|
||||
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
|
||||
those horizontally or vertically neighboring. The same letter cell may not be used more than once.
|
||||
|
||||
For example,
|
||||
Given board =
|
||||
@ -27,8 +26,8 @@ word = "ABCB", -> returns false.
|
||||
Depth First Search in matrix (as multiple sources possible) with backtracking
|
||||
like finding cycle in a directed graph. Maintain a record of path
|
||||
|
||||
Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times
|
||||
Sx = O(L) : stack size is max L
|
||||
Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we
|
||||
do it L times Sx = O(L) : stack size is max L
|
||||
*/
|
||||
|
||||
public class WordSearch {
|
||||
@ -52,8 +51,7 @@ public class WordSearch {
|
||||
int yi = y + dy[i];
|
||||
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
|
||||
boolean exists = doDFS(xi, yi, nextIdx + 1);
|
||||
if (exists)
|
||||
return true;
|
||||
if (exists) return true;
|
||||
}
|
||||
}
|
||||
visited[x][y] = false;
|
||||
@ -68,12 +66,10 @@ public class WordSearch {
|
||||
if (board[i][j] == word.charAt(0)) {
|
||||
visited = new boolean[board.length][board[0].length];
|
||||
boolean exists = doDFS(i, j, 1);
|
||||
if (exists)
|
||||
return true;
|
||||
if (exists) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user