简单的算法问题,第一次发贴 大家多多支持!

fantasyzheng 2009-08-13 01:26:11
要求输出格式为
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
要求:简单的for循环应用,不要用引用API的方法
扩展: 可以任意输出此格式!比如 25,输出5行5列按此排列!
...全文
112 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
linhui9010 2009-08-13
  • 打赏
  • 举报
回复
lz第一次发帖 就gf了!
bigbug9002 2009-08-13
  • 打赏
  • 举报
回复
F:\java>java  CycleSquare
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
bigbug9002 2009-08-13
  • 打赏
  • 举报
回复
import java.util.*;
public class CycleSquare{
public static void main(String[] args) {
int[][] result=getSquare(5);
printSquare(result);
}
public static int[][]getSquare(int x){
int[][] direction={{0 , 1}, //offset of row and column when direction is east.
{1 , 0}, //south
{0 ,-1}, //west
{-1, 0} //north
};
int[][] result=new int[x][x];
int row=0,column=0;
int num=1;
int d=0; //east
int nextRow=0,nextColumn=0;

while(num<=x*x){
result[row][column]=num++;
nextRow=row+direction[d][0];
nextColumn=column+direction[d][1];
if(nextRow==x||nextColumn==x||nextRow<0||nextColumn<0||result[nextRow][nextColumn]!=0){
d=(d+1)%4;
}
row+=direction[d][0];
column+=direction[d][1];
}
return result;
}

public static void printSquare(int[][] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.printf("%5d",arr[i][j]);
}
System.out.println();
}
}

}


F:\java>java CycleSquare
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
【如鱼饮水】 2009-08-13
  • 打赏
  • 举报
回复
螺旋矩阵
http://topic.csdn.net/u/20080114/22/48153ab5-a7ea-4246-972b-5e4c9f868430.html
fantasyzheng 2009-08-13
  • 打赏
  • 举报
回复
麻烦把详细的代码写出来 谢谢了
awusoft 2009-08-13
  • 打赏
  • 举报
回复
四个循环,
i,j++;
i++,j;
i,j--;
i--,j;
fantasyzheng 2009-08-13
  • 打赏
  • 举报
回复
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
格式没打规范,重打下!

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧