Java One of easiest way to code this without thinking edge case


#1

Comment body goes here.Preformatted text
sr=start row, sc=start column, er= end row and ec= end column

public  ArrayList<ArrayList<Integer>> generateMatrix(int A) {
	int count=1;
	
	ArrayList<ArrayList<Integer>> l= new ArrayList<>();
	for(int i=1;i<=A;i++) {
		ArrayList<Integer> l1= new ArrayList<>();
		for(int j=0;j<A;j++) {
			l1.add(0);
		}
		l.add(l1);
	}
	int sr=0;
	 int sc=0;
	  int er=A-1;
	  int ec=A-1;
	  int i=0;
	  int j=0, k=0,w=0;
	  while(count<=A*A) {
		  if(sr==sc && er==ec && sr==er) {
			  l.get(sr).set(sc, count);
			  count++;
		  }
		  
		  i=sc;
		  //  forward
		  while(i<ec) {
			  l.get(sr).set(i, count);
			  count++;
			  i++;
		  }
		  
		  
		  // downward
		  j=sr;
		  while(j<er) {
			  l.get(j).set(ec, count);
			  count++;
			  j++;
		  }
		  
		  
		  // backward
		  k=ec;
		  while(k>sc) {
			  
			  l.get(er).set(k, count);
			  count++;
			  k--;
		  }
		  
		  
		  
		  // upward
		  w=er;
		  while(w>sr) {
			  l.get(w).set(sc, count);
			  count++;
			  w--;
		  }
		  sr++;
		  sc++;
		  er--;
		  ec--;
		  
	  }
	  return l;
	
}