I wrote the following code. The key should display all the diagonals that start from the top, and then move along the diagonals that start from the sides. I included a method that combines two angles to intersect the diagonals northwest - southeast and northeast - southwest and autonomous methods for traversing the corresponding angles.
public static void main(String[] args){ int[][] m = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; printDiagonals(m, DiagonalDirection.NEtoSW, new DiagonalVisitor() { public void visit(int x, int y, int[][] m) { System.out.println(m[x][y]); } }); } public enum DiagonalDirection{ NWToSE, NEtoSW } private static abstract class DiagonalVisitor{ public abstract void visit(int x, int y, int[][] m); } public static void printDiagonals(int[][] m, DiagonalDirection d, DiagonalVisitor visitor){ int xStart = d==DiagonalDirection.NEtoSW ? 0 : m.length-1; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart>=0 && xStart<m.length){ xLoop = xStart; yLoop = 0; xStart++; }else if(yStart<m[0].length){ xLoop = d==DiagonalDirection.NEtoSW ? m.length-1 : 0; yLoop = yStart; yStart++; }else break; for(;(xLoop<m.length && xLoop>=0)&&yLoop<m[0].length; xLoop=d==DiagonalDirection.NEtoSW ? xLoop-1 : xLoop+1, yLoop++){ visitor.visit(xLoop, yLoop, m); } } } public static void printDiagonalsNEtoSW(int[][] m, DiagonalVisitor visitor){ int xStart = 0; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart<m.length){ xLoop = xStart; yLoop = 0; xStart++; }else if(yStart<m[0].length){ xLoop = m.length-1; yLoop = yStart; yStart++; }else break; for(;xLoop>=0 && yLoop<m[0].length; xLoop--, yLoop++){ visitor.visit(xLoop, yLoop, m); } } } public static void printDiagonalsNWtoSE(int[][] m, DiagonalVisitor visitor){ int xStart = m.length-1; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart>=0){ xLoop = xStart; yLoop = 0; xStart--; }else if(yStart<m[0].length){ xLoop = 0; yLoop = yStart; yStart++; }else break; for(;xLoop<m.length && yLoop<m[0].length; xLoop++, yLoop++){ visitor.visit(xLoop, yLoop, m); } } }
source share