Skip to content

Instantly share code, notes, and snippets.

@hesic73
Created February 5, 2024 01:21
Show Gist options
  • Save hesic73/2a71f5a5243cef09740abf3d4ac2141d to your computer and use it in GitHub Desktop.
Save hesic73/2a71f5a5243cef09740abf3d4ac2141d to your computer and use it in GitHub Desktop.
Template for 2D Grid Problems on LeetCode
import java.util.Iterator;
import java.util.NoSuchElementException;
class Solution {
private static boolean withBounds(int x, int y, int m, int n) {
return x >= 0 && x < m && y >= 0 && y < n;
}
private static int flatten(int x, int y, int m, int n) {
return x * n + y;
}
private static Point unflatten(int index, int m, int n) {
int x = index / n;
int y = index % n;
return new Point(x, y);
}
private static class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
private static class AdjacentPointGenerator implements Iterable<Point> {
private final int x;
private final int y;
private final int m;
private final int n;
public AdjacentPointGenerator(int x, int y, int m, int n) {
this.x = x;
this.y = y;
this.m = m;
this.n = n;
}
public AdjacentPointGenerator(Point point, int m, int n) {
this.x = point.x;
this.y = point.y;
this.m = m;
this.n = n;
}
@Override
public Iterator<Point> iterator() {
return new Iterator<Point>() {
private int index = 0;
// Directions represented as {dx, dy}
private final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// Next point to return
private Point nextPoint = null;
private boolean isValid(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
@Override
public boolean hasNext() {
if (nextPoint != null) {
// Already found the next valid point
return true;
}
while (index < directions.length) {
int nextX = x + directions[index][0];
int nextY = y + directions[index][1];
if (isValid(nextX, nextY)) {
// Found the next valid point, store it and stop searching
nextPoint = new Point(nextX, nextY);
index++; // Prepare for the next call
return true;
}
index++; // Move to the next direction if current is out of bounds
}
return false; // No more valid points
}
@Override
public Point next() {
if (nextPoint != null || hasNext()) {
Point pointToReturn = nextPoint;
nextPoint = null; // Reset for the next iteration
return pointToReturn;
}
throw new NoSuchElementException("No more elements");
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment