import java.util.*;
class LuoxuanShuzuTest
{
public static void main(String[] args)
{
int [][] arr = LuoxuanShuzu.luoxuanShuzu(3,3);
for(int i=0;i<arr.length;i++)
{
System.out.println(Arrays.toString(arr[i]));
}
}
}
class LuoxuanShuzu
{
public static int[][] luoxuanShuzu(int x,int y)
{
int count = 1;
int[][] arr = new int[x][y];
fangxiang1(arr,0,0,count);
return arr;
}
public static void fangxiang1(int[][] arr,int i,int j,int count)
{
//赋值后count自加
arr[i][j] = count;
count++;
//如果向右移到达边界
if(j+1 == arr[i].length)
{
//同时向下移到达边界则只有一个元素,返回
if (i+1 == arr.length)
{
return;
}
//向下移
else
{
i++;
fangxiang2(arr,i,j,count);
}
}
//右边元素为空,则赋值右边元素
else if (arr[i][j+1] == 0)
{
j++;
fangxiang1(arr,i,j,count);
}
//否则向下移动
else if (arr[i+1][j] == 0)
{
i++;
fangxiang2(arr,i,j,count);
}
else
{
return;
}
}
public static void fangxiang2(int[][] arr,int i,int j,int count)
{
//赋值后count自加
arr[i][j] = count;
count++;
if(i+1 == arr.length)
{
if (j-1 == -1)
{
return;
}
else
{
j--;
fangxiang3(arr,i,j,count);
}
}
else if (arr[i+1][j] != 0){
if(arr[i][j-1] != 0){
return;
}
else{
j--;
fangxiang3(arr,i,j,count);
}
}
else
{
i++;
fangxiang2(arr,i,j,count);
}
}
public static void fangxiang3(int[][] arr,int i,int j,int count)
{
//赋值后count自加
arr[i][j] = count;
count++;
if(j == 0)
{
if(arr[i-1][j] != 0)
{
return;
}
else
{
i--;
fangxiang4(arr,i,j,count);
}
}
else if (arr[i][j-1] != 0)
{
if(arr[i-1][j] != 0)
{
return;
}
else
{
i--;
fangxiang4(arr,i,j,count);
}
}
else
{
j--;
fangxiang3(arr,i,j,count);
}
}
public static void fangxiang4(int[][] arr,int i,int j,int count)
{
//赋值后count自加
arr[i][j] = count;
count++;
if(arr[i-1][j] != 0)
{
if (arr[i][j+1] != 0)
{
return;
}
else
{
j++;
fangxiang1(arr,i,j,count);
}
}
else
{
i--;
fangxiang4(arr,i,j,count);
}
}
}
|
|