java实现的顺时针/逆时针打印矩阵操作示例
java实现的顺时针/逆时针打印矩阵操作。分享给大家供大家参考,具体如下:
publicclassSnakeMatrix{ /** *定义矩阵的阶数 */ privateintn; //填充矩阵的值 privateintk=1; privateint[][]data; /** *定义矩阵移动的方向 */ publicenumDirection{ left,right,up,down, } SnakeMatrix(intn){ this.n=n; data=newint[n][n]; } publicvoidclockwisePrintMatrix(){ //定义行数 introwLen=data.length; //定义列数 intcolumnLen=data.length; //移动方向 Directiondirection=Direction.right; //定义上边界 intupBound=0; //定义下边界 intdownBound=rowLen-1; //定义左边界 intleftBound=0; //定义右边界 intrightBound=columnLen-1; //矩阵当前行数 introw=0; //矩阵当前列数 intcolumn=0; while(true){ data[row][column]=k++; if(upBound==downBound&&leftBound==rightBound){ //System.out.println("upBound:"+upBound+"downBound:"+downBound+"leftBound:"+leftBound+"rightBound:"+rightBound); break; } switch(direction){ caseright: if(columnupBound){ --row; }else{ ++column; direction=Direction.right; ++leftBound; } break; caseleft: if(column>leftBound){ --column; }else{ --row; direction=Direction.up; --downBound; } break; default: break; } } for(inti=0;i upBound){ row--; }else{ direction=Direction.left; column--; rightBound--; } break; caseleft: if(column>leftBound){ column--; }else{ direction=Direction.down; row++; upBound++; } break; default: break; } } for(inti=0;i 首先呢上面是定义一个工具类,
publicclassMainActivityextendsAppCompatActivity{ @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intnumber=5; SnakeMatrixsnakeMatrix=newSnakeMatrix(number); snakeMatrix.anticlockwisePrintMatrix(); //snakeMatrix.clockwisePrintMatrix(); } }直接进行使用,有两个方法,一个正序一个倒序
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。