Open In App

Anti-aliased Line | Xiaolin Wu’s algorithm

Last Updated : 27 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Anti-Aliased Line Drawing

Below is the image showing line drawn with Bresenham’s line algorithm (left) and Xiaolin Wu’s line algorithm (right) which smooths the line. Which one looks better to you ?

AALine

Anti Aliasing concept

Suppose we want to draw a line from point(1 , 1) to point(8 , 4) with rectangular edges. The ideal line would be the one shown in figure A . Since I want to display it on screen I cannot use that. Line needs to go through a process called

Rasterization

which would determine color of individual pixels. Several algorithms can be used like

Bresenham’s Line Algorithm

,

Digital Differential Analyzer

, Xiaolin Wu’s line algorithm , Gupta-Sproull algorithm . Later two perform anti-aliasing or line smoothing. The result produced by first two algorithm is show in figure B.

solidfillfirstrast

There are few problems in Line( figure B ). 1. Pixel (4,2) has less coverage than Pixel (3,2), yet they’re both drawn fully black. 2. Pixel (2,2) has almost as much coverage as (4,2), and yet it’s drawn fully white. To overcome these drawbacks and produce a much smoother looking line we use Xiaolin Wu’s line algorithm

Xiaolin Wu’s line algorithm

Consider the figure shown below which is drawn using Bresenham’s Line Generation Algorithm . Take a segment and its initial coordinate x. By the X in the loop is added 1 towards the end of the segment. At each step, the error is calculated – the distance between the actual y-coordinate at that location and the nearest grid cell. If the error does not exceed half the height of the cell, it is filled. That’s the whole algorithm.

original-a04cf694-556504fba7413

We will modify this algorithm so that it can produce an anti-aliased line . Xiaolin Wu’s line algorithm is characterized by the fact that at each step of the calculation is carried out for the two closest to the line of pixels, and they are colored with different intensity, depending on the distance. Current intersection middle pixel intensity gives 100% if the pixel is within 0.9 pixel, the intensity will be 10%. In other words, one hundred percent of the intensity is divided between the pixels which limit vector line on both sides.

original-ccf57794-556504fc0787f

In the picture the red and green color shows the distance to the two adjacent pixels. To calculate the error, you can use floating point and take the error value of the fractional part.

NOTE:

The following implementation uses

SDL

library to draw pixels on screen . If you are on debian system like ubuntu just run following command to install SDL library.

sudo apt-get install libsdl2-dev

To build use

gcc filename.c -lSDL2

Note:

If the projection of the segment on the x-axis is less than the projection on the y-axis, or the beginning and end of the segment are swapped, then the algorithm will not work. To avoid this, you need to check the direction of the vector and its slope, and then swap the coordinates of the line , ultimately to reduce everything to some one or at least two cases. Following algorithm assumes that only integer co-ordinates will be given as inputs since pixel value cannot be floating point.

CPP
#include <SDL2/SDL.h>

// SDL stuff
SDL_Window* pWindow = 0;
SDL_Renderer* pRenderer = 0;

// swaps two numbers
void swap(int* a , int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// returns absolute value of number
float absolute(float x)
{
    if (x < 0) return -x;
    else return x;
}

// returns integer part of a floating point number
int iPartOfNumber(float x)
{
    return (int)x;
}

// rounds off a number
int roundNumber(float x)
{
    return iPartOfNumber(x + 0.5);
}

// returns fractional part of a number
float fPartOfNumber(float x)
{
    if (x > 0) return x - iPartOfNumber(x);
    else return x - (iPartOfNumber(x)+1);
}

// returns 1 - fractional part of number
float rfPartOfNumber(float x)
{
    return 1 - fPartOfNumber(x);
}

// draws a pixel on screen of given brightness
// 0 <= brightness <= 1. We can use your own library
// to draw on screen
void drawPixel(int x, int y, float brightness)
{
    int c = 255 * brightness;
    SDL_SetRenderDrawColor(pRenderer, c, c, c, 255);
    SDL_RenderDrawPoint(pRenderer, x, y);
}

void drawAALine(int x0, int y0, int x1, int y1)
{
    int steep = absolute(y1 - y0) > absolute(x1 - x0);

    // swap the co-ordinates if slope > 1 or we
    // draw backwards
    if (steep)
    {
        swap(&x0, &y0);
        swap(&x1, &y1);
    }
    if (x0 > x1)
    {
        swap(&x0, &x1);
        swap(&y0, &y1);
    }

    // compute the slope
    float dx = x1 - x0;
    float dy = y1 - y0;
    float gradient = dy / dx;
    if (dx == 0.0)
        gradient = 1;

    int xpxl1 = x0;
    int xpxl2 = x1;
    float intersectY = y0;

    // main loop
    if (steep)
    {
        int x;
        for (x = xpxl1; x <= xpxl2; x++)
        {
            // pixel coverage is determined by fractional
            // part of y co-ordinate
            drawPixel(iPartOfNumber(intersectY), x,
                rfPartOfNumber(intersectY));
            drawPixel(iPartOfNumber(intersectY) - 1, x,
                fPartOfNumber(intersectY));
            intersectY += gradient;
        }
    }
    else
    {
        int x;
        for (x = xpxl1; x <= xpxl2; x++)
        {
            // pixel coverage is determined by fractional
            // part of y co-ordinate
            drawPixel(x, iPartOfNumber(intersectY),
                rfPartOfNumber(intersectY));
            drawPixel(x, iPartOfNumber(intersectY) - 1,
                fPartOfNumber(intersectY));
            intersectY += gradient;
        }
    }

}

// Driver code
int main(int argc, char* args[])
{

    SDL_Event event;

    // initialize SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) >= 0)
    {
        // if succeeded create our window
        pWindow = SDL_CreateWindow("Anti-Aliased Line ",
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            640, 480,
            SDL_WINDOW_SHOWN);

        // if the window creation succeeded create our renderer
        if (pWindow != 0)
            pRenderer = SDL_CreateRenderer(pWindow, -1, 0);
    }
    else
        return 1; // sdl could not initialize

    while (1)
    {
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;

        // Sets background color to white
        SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255);
        SDL_RenderClear(pRenderer);

        // draws a black AALine
        drawAALine(80, 200, 550, 150);

        // show the window
        SDL_RenderPresent(pRenderer);
    }

    // clean up SDL
    SDL_Quit();
    return 0;
}
Java
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

// Class to represent a pixel
class Pixel {
    int x, y;
    float brightness;

    public Pixel(int x, int y, float brightness) {
        this.x = x;
        this.y = y;
        this.brightness = brightness;
    }
}

public class Main extends JFrame {

    private BufferedImage canvas;

    // Constructor to set up the canvas and the JFrame
    public Main() {
        canvas = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
        setContentPane(new JLabel(new ImageIcon(canvas)));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(640, 480);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    // Method to draw a pixel on the canvas with a given brightness
    // 0 <= brightness <= 1
    public void drawPixel(int x, int y, float brightness) {
        int c = (int)(255 * brightness);
        int color = new Color(c, c, c).getRGB();
        canvas.setRGB(x, y, color);
    }

    // Method to swap two integers
    public void swap(Pixel p1, Pixel p2) {
        Pixel temp = new Pixel(p1.x, p1.y, p1.brightness);
        p1.x = p2.x;
        p1.y = p2.y;
        p1.brightness = p2.brightness;
        p2.x = temp.x;
        p2.y = temp.y;
        p2.brightness = temp.brightness;
    }

    // Method to get the absolute value of a number
    public float absolute(float x) {
        if (x < 0) return -x;
        else return x;
    }

    // Method to get the integer part of a floating point number
    public int iPartOfNumber(float x) {
        return (int)x;
    }

    // Method to round off a number
    public int roundNumber(float x) {
        return iPartOfNumber(x + 0.5f);
    }

    // Method to get the fractional part of a number
    public float fPartOfNumber(float x) {
        if (x > 0) return x - iPartOfNumber(x);
        else return x - (iPartOfNumber(x)+1);
    }

    // Method to get 1 - fractional part of number
    public float rfPartOfNumber(float x) {
        return 1 - fPartOfNumber(x);
    }

    // Method to draw an anti-aliased line
    public void drawAALine(int x0, int y0, int x1, int y1) {
        boolean steep = absolute(y1 - y0) > absolute(x1 - x0);

        Pixel p1 = new Pixel(x0, y0, 1);
        Pixel p2 = new Pixel(x1, y1, 1);

        // Swap the coordinates if slope > 1 or we draw backwards
        if (steep) {
            swap(p1, p2);
        }
        if (p1.x > p2.x) {
            swap(p1, p2);
        }

        // Compute the slope
        float dx = p2.x - p1.x;
        float dy = p2.y - p1.y;
        float gradient = dy / dx;
        if (dx == 0.0)
            gradient = 1;

        float intersectY = p1.y;

        // Main loop
        if (steep) {
            for (int x = p1.x; x <= p2.x; x++) {
                // Pixel coverage is determined by fractional part of y coordinate
                drawPixel(iPartOfNumber(intersectY), x, rfPartOfNumber(intersectY));
                drawPixel(iPartOfNumber(intersectY) - 1, x, fPartOfNumber(intersectY));
                intersectY += gradient;
            }
        } else {
            for (int x = p1.x; x <= p2.x; x++) {
                // Pixel coverage is determined by fractional part of y coordinate
                drawPixel(x, iPartOfNumber(intersectY), rfPartOfNumber(intersectY));
                drawPixel(x, iPartOfNumber(intersectY) - 1, fPartOfNumber(intersectY));
                intersectY += gradient;
            }
        }
    }

    // Driver code
    public static void main(String[] args) {
        Main frame = new Main();
        frame.drawAALine(80, 200, 550, 150);
    }
}
Python
# Importing required modules
import pygame
import sys

# Function to swap two numbers
def swap(a, b):
    return b, a

# Function to return absolute value of number
def absolute(x):
    return abs(x)

# Function to return integer part of a floating point number
def iPartOfNumber(x):
    return int(x)

# Function to round off a number
def roundNumber(x):
    return round(x)

# Function to return fractional part of a number
def fPartOfNumber(x):
    return x - iPartOfNumber(x)

# Function to return 1 - fractional part of number
def rfPartOfNumber(x):
    return 1 - fPartOfNumber(x)

# Function to draw a pixel on screen of given brightness
def drawPixel(screen, x, y, brightness):
    c = int(255 * brightness)
    pygame.draw.line(screen, (c, c, c), (x, y), (x+1, y))

# Function to draw an anti-aliased line
def drawAALine(screen, x0, y0, x1, y1):
    steep = absolute(y1 - y0) > absolute(x1 - x0)

    if steep:
        x0, y0 = swap(x0, y0)
        x1, y1 = swap(x1, y1)

    if x0 > x1:
        x0, x1 = swap(x0, x1)
        y0, y1 = swap(y0, y1)

    dx = x1 - x0
    dy = y1 - y0
    gradient = dy / dx if dx != 0 else 1

    xpxl1 = x0
    xpxl2 = x1
    intersectY = y0

    if steep:
        for x in range(xpxl1, xpxl2 + 1):
            drawPixel(screen, iPartOfNumber(intersectY), x, rfPartOfNumber(intersectY))
            drawPixel(screen, iPartOfNumber(intersectY) - 1, x, fPartOfNumber(intersectY))
            intersectY += gradient
    else:
        for x in range(xpxl1, xpxl2 + 1):
            drawPixel(screen, x, iPartOfNumber(intersectY), rfPartOfNumber(intersectY))
            drawPixel(screen, x, iPartOfNumber(intersectY) - 1, fPartOfNumber(intersectY))
            intersectY += gradient

# Main function
def main():
    pygame.init()

    # Creating a window
    screen = pygame.display.set_mode((640, 480))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Setting background color to white
        screen.fill((255, 255, 255))

        # Drawing a black anti-aliased line
        drawAALine(screen, 80, 200, 550, 150)

        # Updating the window
        pygame.display.flip()

if __name__ == "__main__":
    main()
JavaScript
// Function to draw a pixel on the canvas with given brightness
// 0 <= brightness <= 1
function drawPixel(ctx, x, y, brightness) {
    const c = Math.floor(255 * brightness);
    ctx.fillStyle = `rgb(${c}, ${c}, ${c})`;
    ctx.fillRect(x, y, 1, 1);
}

function drawAALine(ctx, x0, y0, x1, y1) {
    const steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);

    if (steep) {
        [x0, y0] = [y0, x0];
        [x1, y1] = [y1, x1];
    }

    if (x0 > x1) {
        [x0, x1] = [x1, x0];
        [y0, y1] = [y1, y0];
    }

    const dx = x1 - x0;
    const dy = y1 - y0;
    const gradient = dy / dx || 1;

    let xpxl1 = Math.floor(x0);
    let xpxl2 = Math.floor(x1);
    let intersectY = y0;

    if (steep) {
        for (let x = xpxl1; x <= xpxl2; x++) {
            drawPixel(ctx, Math.floor(intersectY), x, rfPartOfNumber(intersectY));
            drawPixel(ctx, Math.floor(intersectY) - 1, x, fPartOfNumber(intersectY));
            intersectY += gradient;
        }
    } else {
        for (let x = xpxl1; x <= xpxl2; x++) {
            drawPixel(ctx, x, Math.floor(intersectY), rfPartOfNumber(intersectY));
            drawPixel(ctx, x, Math.floor(intersectY) - 1, fPartOfNumber(intersectY));
            intersectY += gradient;
        }
    }
}

// Main function to draw the anti-aliased line
function main() {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // Draws the white background
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Draws the black anti-aliased line
    drawAALine(ctx, 80, 200, 550, 150);
}

// Execute the main function when the DOM content is loaded
document.addEventListener('DOMContentLoaded', main);

// This code is contributed by SHIVAM GUPTA

Output:

outputAALine


Previous Article
Next Article

Similar Reads

Anti Clockwise spiral traversal of a binary tree
Given a binary tree, the task is to print the nodes of the tree in an anti-clockwise spiral manner. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 1 4 5 6 7 3 2 Input: 1 / \ 2 3 / / \ 4 5 6 / \ / / \ 7 8 9 10 11 Output: 1 7 8 9 10 11 3 2 4 5 6 Approach: The idea is to use two variables i initialized to 1 and j initialized to the height of tree
15+ min read
Return an array of anti-diagonals of given N*N square matrix
Given a square matrix of size N*N, return an array of its anti-diagonals. For better understanding let us look at the image given below: Examples: Input : Output : 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Approach 1:To solve the problem mentioned above we have two major observations. The first one is, some diagonals start from the zeroth row for each
10 min read
Anti-perfect Number
Given a number N, the task is to check if N is an Anti-perfectNumber or not. If N is an Anti-perfectNumber then print "Yes" else print "No". An anti-perfect Number is a number that is equal to the sum of the reverse of its proper divisors. Examples: Input: N = 244 Output: Yes Explanation: proper divisors of 24 are 1, 2, 4, 61, 122 sum of their reve
7 min read
Anti-Symmetric Relation on a Set
A relation is a subset of the cartesian product of a set with another set. A relation contains ordered pairs of elements of the set it is defined on. To learn more about relations refer to the article on "Relation and their types". What is an Anti-Symmetric Relation? A relation R on a set A is called anti-symmetric relation if ∀ a, b ∈ A, if (a, b)
6 min read
Make String Anti-Palindrome
Given a string S of length N is said to be an Anti-palindrome string if, for each 0 ? i ? N-1, Si != S(N - 1 ? i). The task is to print Anti-Palindrome String formed, If it is not possible to find print "-1" Examples: Input: S = "abdcccdb"Output: "cbbaccdd"Explanation: cbbaccdd is an Anti-palindrome string as for each 0 ? i ? N-1, Si != S(N-1?i). I
6 min read
Check matrix transformation by flipping sub-matrices along the principal or anti-diagonal
Given two matrices mat1[][] and mat2[][] of size N*M, the task is check if it is possible to transform mat1 into mat2 by selecting any square sub-matrix from mat1 and flipping it along its principal diagonal or anti-diagonal. Examples: Input: N = 2, M = 3, mat1[][] = {{1, 2, 3}, {4, 5, 6}}, mat2[][] = {{1, 4, 3}, {6, 5, 2}}Output: YESExplanation: I
13 min read
What is Anti-aliasing?
Antialiasing is a technique used in computer graphics to remove the aliasing effect. The aliasing effect is the appearance of jagged edges or “jaggies” in a rasterized image (an image rendered using pixels). The problem of jagged edges technically occurs due to distortion of the image when scan conversion is done with sampling at a low frequency, w
6 min read
Slope of the line parallel to the line with the given slope
Given an integer m which is the slope of a line, the task is to find the slope of the line which is parallel to the given line. Examples: Input: m = 2 Output: 2 Input: m = -3 Output: -3 Approach: Let P and Q be two parallel lines with equations y = m1x + b1, and y = m2x + b2 respectively. Here m1 and m2 are the slopes of the lines respectively. Now
3 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Equation of a straight line passing through a point and making a given angle with a given line
Given four integers a, b, c representing coefficients of a straight line with equation (ax + by + c = 0), the task is to find the equations of the two straight lines passing through a given point [Tex](x1, y1) [/Tex]and making an angle ? with the given straight line. Examples: Input: a = 2, b = 3, c = -7, x1 = 4, y1 = 9, ? = 30Output: y = -0.49x +1
15+ min read
Scan conversion of Line and Line Drawing algorithms
SCAN Conversion of Line : A line connects two points.It is a basic element in graphics.You'll need two spots between which to draw a line to draw a line . A line, or line segment, can be uniquely described by two points, according to geometry. We also know from algebra that a line can be defined by a slope, commonly denoted by the letter m, and a y
4 min read
Level order traversal line by line (Using One Queue)
Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line. Example: Input: Output:12 34 5 Table of Content [Expected Approach – 1] Using Queue with delimiter – O(n) Time and O(n) Space[Expected Approach – 2] Using Queue without delimiter – O(n) Time and O(n) Space[Expected Approach – 1] Using Queue with delimiter – O(
12 min read
Print level order traversal line by line
Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line. Example: Input: Output:12 34 5 Table of Content [Naive Approach] - Using Recursion - O(n^2) Time and O(n) Space[Expected Approach – 1] Using Queue with delimiter – O(n) Time and O(n) Space[Expected Approach – 2] Using Queue without delimiter – O(n) Time and O(
9 min read
Level order traversal line by line (Using Two Queues)
Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line. Example: Input: Output:12 34 5 Approach: The idea is to use two queues to traverse in Level order manner. We will insert the first level in first queue and print it and while popping from the first queue insert its left and right nodes into the second queue. N
9 min read
Comparisons between DDA and Bresenham Line Drawing algorithm
In lighting tricks, there are 2 algorithmic rules used for drawing a line over the screen that's DDA stands for Digital Differential Analyser algorithmic rule and Bresenham line algorithm. The main distinction between DDA algorithm and Bresenham line algorithm is that, the DDA algorithmic rule uses floating purpose values whereas in Bresenham, sphe
1 min read
Cohen-Sutherland vs. Liang-Barsky line clipping algorithm
Cohen-Sutherland Line Clipping Algorithm : It is a line clipping algorithm. In which 2-D space (in which line resides) is divided into 9 regions and then the lines and portions of lines which are visible in the central region of interest are determined efficiently. It quickly detects and dispenses with two common and trivial cases. It was developed
2 min read
Computer Graphics - Scan Line Algorithm in 3D (Hidden Surface Removal)
This algorithm is based on the Image-space method and concept of coherence. As its name suggests itself Scan-line algorithm, so it processes one line at a time rather than processing one pixel(a point on raster display) at a time. The algorithm works as follows: Here each point at which the scan- line intersects the polygon surfaces are examined(pr
4 min read
Illustration for tracing all the 8 octaves in Bresenham's line algorithm
Prerequisite: Bresenham's Line Generation Algorithm In this article, we will understand how Bresenham's Line Algorithm is used to find all the octaves. While understanding the algorithm considers only the case where coordinate of the two points P0(x0, y0) and P1(x1, y1) such that x0 < x1 and y0 < y1. The task is to find all the intermediate p
12 min read
Appel's Hidden Line Removal Algorithm
Overview : In Hidden Surface Algorithms Taxonomy Removal the resultant object may be represented as a collection of contour lines, e.g. Appeal or Watkins' technique, or Encarnacao's Priority method requires to be input data as triangles, and calculates each part of the drawing in turn, from front of surface.In a computer representation, solid thing
4 min read
Tarjan's off-line lowest common ancestors algorithm
Prerequisite : LCA basics, Disjoint Set Union by Rank and Path CompressionWe are given a tree(can be extended to a DAG) and we have many queries of form LCA(u, v), i.e., find LCA of nodes ‘u’ and ‘v’.We can perform those queries in O(N + QlogN) time using RMQ, where O(N) time for pre-processing and O(log N) for answering the queries, where N = numb
15+ min read
Klee's Algorithm (Length Of Union Of Segments of a line)
Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we take the union of all the line segments, we cover di
9 min read
DDA Line generation Algorithm in Computer Graphics
Introduction : DDA (Digital Differential Analyzer) is a line drawing algorithm used in computer graphics to generate a line segment between two specified endpoints. It is a simple and efficient algorithm that works by using the incremental difference between the x-coordinates and y-coordinates of the two endpoints to plot the line. The steps involv
12 min read
Mid-Point Line Generation Algorithm
Given coordinate of two points A(x1, y1) and B(x2, y2) such that x1 < x2 and y1 < y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. DDA algorithm for line drawingIntroduction to Bresenha
11 min read
Bresenham’s Line Generation Algorithm
Given the coordinate of two points A(x1, y1) and B(x2, y2). The task is to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates. Examples: Input : A(0,0), B(4,4)Output : (0,0), (1,1), (2,2), (3,3), (4,4) Input : A(0,0), B(4,2)Output : (0,0), (1,0), (2,1), (3,1)
14 min read
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Description:- In this algorithm, we are given 9 regions on the screen. Out of which one region is of the window and the rest 8 regions are around it given by 4 digit binary.  The division of the regions are based on (x_max, y_max) and (x_min, y_min). The central part is the viewing region or window, all the lines which lie within this region are co
15+ min read
Closest Pair of Points using Sweep Line Algorithm
Given an array of N points in the plane, the task is to find a pair of points with the smallest distance between them, where the distance between two points (x1, y1) and (x2, y2) can be calculated as [(x1 - x2) ^ 2] + [(y1 - y2) ^ 2]. Examples: Input: P[] = { {1, 2}, {2, 3}, {3, 4}, {5, 6}, {2, 1} }Output: The smallest distance is 2.Explanation: Di
8 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Practice Tags :
three90RightbarBannerImg