Created
January 29, 2019 15:27
-
-
Save summit87/94f3861a9f53efac882d93d1421d88ce to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package mattrix; | |
| import java.util.LinkedList; | |
| import java.util.Queue; | |
| public class RotTomato { | |
| public static void main(String[] args) { | |
| // | |
| int[][] mat = {{2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; | |
| int row = 3; | |
| int col = 5; | |
| rotTomato(mat, row, col); | |
| } | |
| private static void rotTomato(int[][] mat, int row, int col) { | |
| int time = 0; | |
| Queue<Pair> q = new LinkedList<>(); | |
| for (int i = 0; i < row; i++) { | |
| for (int j = 0; j < col; j++) { | |
| if (mat[i][j] == 2) { | |
| Pair p = new Pair(i, j, 0); | |
| q.add(p); | |
| } | |
| } | |
| } | |
| while (!q.isEmpty()) { | |
| Pair p1 = q.poll(); | |
| time = p1.getTime(); | |
| int p1r = p1.getR(); | |
| int p1c = p1.getC(); | |
| // Moving right; | |
| if (p1c + 1 < col && mat[p1r][p1c + 1] == 1) { | |
| mat[p1r][p1c + 1] = 2; | |
| int t = time + 1; | |
| Pair p2 = new Pair(p1r, p1c + 1, t); | |
| q.add(p2); | |
| } | |
| // Moving down | |
| if (p1r + 1 < row && mat[p1r + 1][p1c] == 1) { | |
| mat[p1r + 1][p1c] = 2; | |
| int t = time + 1; | |
| Pair p2 = new Pair(p1r + 1, p1c, t); | |
| q.add(p2); | |
| } | |
| // Moving left | |
| if (p1c - 1 >= 0 && mat[p1r][p1c - 1] == 1) { | |
| mat[p1r][p1c - 1] = 2; | |
| int t = time + 1; | |
| Pair p2 = new Pair(p1r, p1c - 1, t); | |
| q.add(p2); | |
| } | |
| // Moving Up | |
| if (p1r - 1 >= 0 && mat[p1r - 1][p1c] == 1) { | |
| mat[p1r - 1][p1c] = 2; | |
| int t = time + 1; | |
| Pair p2 = new Pair(p1r - 1, p1c, t); | |
| q.add(p2); | |
| } | |
| } | |
| for (int i = 0; i < row; i++) { | |
| for (int j = 0; j < col; j++) { | |
| if (mat[i][j] == 1) { | |
| System.out.println("Orange are not rotten"); | |
| break; | |
| } | |
| } | |
| } | |
| System.out.println(time); | |
| } | |
| } | |
| class Pair { | |
| private int r; | |
| private int c; | |
| private int time; | |
| public Pair(int r, int c, int time) { | |
| this.r = r; | |
| this.c = c; | |
| this.time = time; | |
| } | |
| public int getR() { | |
| return r; | |
| } | |
| public void setR(int r) { | |
| this.r = r; | |
| } | |
| public int getC() { | |
| return c; | |
| } | |
| public void setC(int c) { | |
| this.c = c; | |
| } | |
| public int getTime() { | |
| return time; | |
| } | |
| public void setTime(int time) { | |
| this.time = time; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment