Created
November 10, 2013 22:48
-
-
Save arikrak/7404970 to your computer and use it in GitHub Desktop.
An answer to the StackOverflow and Learneroo question: http://www.learneroo.com/courses/29/nodes/221
This file contains 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
import java.util.*; | |
class DistanceZ { | |
static void minArray(int[][] square){ | |
int w = square.length; | |
for(int times = 0; times<w; times++){ | |
for(int i =0; i<w;i++){ | |
for(int j=0;j<w;j++){ | |
square[i][j] = minCell(square, i, j); | |
} | |
} | |
} | |
printArray(square); | |
} | |
private static void printArray(int[][] square) { | |
int w = square.length; | |
for(int i =0; i<w;i++){ | |
for(int j=0;j<w;j++){ | |
System.out.print(square[i][j] + " "); | |
} | |
System.out.println(""); | |
} | |
} | |
static int minCell(int[][] square, int i, int j){ | |
int left,right,up,down = 1000; | |
int min = square[i][j]; | |
if(i>0){ | |
left = square[i-1][j] +1; | |
if(left<min) | |
min=left; | |
} | |
if(i<square.length-1) { | |
right = square[i+1][j] +1; | |
if(right<min) | |
min=right; | |
} | |
if(j>0) { | |
up = square[i][j-1] + 1; | |
if(up<min) | |
min=up; | |
} | |
if(j<square.length-1) { | |
down = square[i][j+1] + 1; | |
if(down<min) | |
min=down; | |
} | |
return min; | |
} | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int t = in.nextInt(); | |
for(int times=0;times<t;times++){ | |
int w = in.nextInt(); | |
int[][] square = new int[w][w]; | |
for(int i =0; i<w;i++){ | |
for(int j=0;j<w;j++){ | |
square[i][j] = in.nextInt(); | |
} | |
} | |
minArray(square); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment