Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int orangesRotting(int[][] grid) {
- HashSet<Point> rotten = new HashSet<Point>();
- HashSet<Point> fresh = new HashSet<Point>();
- for(int r = 0; r < grid.length; r++) {
- for(int c = 0; c < grid[r].length; c++) {
- if (grid[r][c] == 2) {
- rotten.add(new Point(r,c));
- System.out.println("Rotten r: " + r + " c: " + c);
- }
- if ( grid[r][c] == 1) {
- fresh.add(new Point(r,c));
- System.out.println("Fresh r: " + r + " c: " + c);
- }
- }
- }
- if ( fresh.isEmpty()) {
- return 0;
- }
- int count = 0;
- HashSet<Point> newRotten = new HashSet<Point>();
- while (!fresh.isEmpty() && !rotten.isEmpty()) {
- for(Point p: rotten) {
- ArrayList<Point> neighbors = getNeighbors(p, fresh);
- for(Point n: neighbors) {
- newRotten.add(n);
- }
- }
- if(newRotten.isEmpty() && !fresh.isEmpty()) {
- return -1;
- }
- rotten.clear();
- for(Point r: newRotten) {
- rotten.add(r);
- }
- System.out.println(count);
- newRotten.clear();
- count++;
- }
- return count;
- }
- private static ArrayList<Point> getNeighbors(Point p, HashSet<Point> fresh) {
- int r = p.r;
- int c = p.c;
- Point top = new Point(r - 1, c);
- Point bot = new Point(r + 1, c);
- Point left = new Point(r, c + 1);
- Point right = new Point(r, c - 1);
- ArrayList<Point> points = new ArrayList<Point>();
- if (fresh.contains(top)) {
- points.add(top);
- fresh.remove(top);
- }
- if(fresh.contains(left)){
- points.add(left);
- fresh.remove(left);
- }
- if(fresh.contains(right)){
- points.add(right);
- fresh.remove(right);
- }
- if(fresh.contains(bot)) {
- points.add(bot);
- fresh.remove(bot);
- }
- System.out.println(points);
- return points;
- }
- }
- class Point {
- public final int r;
- public final int c;
- public Point (int r, int c ) {
- this.r = r;
- this.c = c;
- }
- public boolean equals(Object b) {
- if ( b == this ) {
- return true;
- }
- Point comp = (Point) b;
- if (this.r == comp.r && this.c == comp.c) {
- return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement