Skip to content

Instantly share code, notes, and snippets.

@toufiq-austcse
Created November 21, 2018 01:45
Show Gist options
  • Select an option

  • Save toufiq-austcse/ad355da1c15dc61e33cb71cb3d94c02c to your computer and use it in GitHub Desktop.

Select an option

Save toufiq-austcse/ad355da1c15dc61e33cb71cb3d94c02c to your computer and use it in GitHub Desktop.

Revisions

  1. toufiq-austcse created this gist Nov 21, 2018.
    50 changes: 50 additions & 0 deletions 2DBFS.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;

    /*In the name of Allah the Most Merciful.
    * Author
    * Md. Toufiqul Islam
    * Dept. Of CSE
    * Ahsanullah University Of Science And Technology
    */
    public class BFS2D {
    static class cell {
    int x;
    int y;

    public cell(int x, int y) {
    this.x = x;
    this.y = y;
    }
    }
    Queue<cell> queue = new LinkedList<cell>();
    boolean isVisited[][] =new boolean[3][3];

    int[] dx = {-1,-1,-1,0,0,1,1,1};
    int[] dy = {-1,0,1,-1,1,-1,0,1};

    void bfs(int x,int y) {
    queue.add(new cell(x, y));
    isVisited[x][y] = true;

    while (queue.size() != 0) {
    cell top = queue.poll();
    System.out.println(top.x + " " + top.y);
    for (int i = 0; i < 8; i++) {
    int tx = top.x + dx[i]; int ty = top.y + dy[i];
    if (tx >= 0 && tx < 3 && ty >= 0 && ty < 3 && !isVisited[tx][ty]) {
    isVisited[tx][ty] = true;

    queue.add(new cell(tx, ty));
    }
    }
    }
    }

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    BFS2D ob = new BFS2D();
    ob.bfs(0,0);
    }
    }