知识点/数据结构 考察点:循环/边界条件
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵:
则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
代码如下:
import java.util.ArrayList;//2018.11.21隔了7个月,又来刷刷算法了
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
int row = matrix.length;//rows表示行数,columns表示列数。
int col = matrix[0].length;
ArrayList<Integer> x = new ArrayList <>();
if(row==0||col==0){
return x;
}
int left =0;int right=col-1;int top=0;int bottom=row-1;
while(left<=right&&top<=bottom){
for(int i=left;i<=right;i++){
x.add(matrix[top][i]);
}
for(int i= top+1;i<=bottom;i++){
x.add(matrix[i][right]);
}
if(top!=bottom){
for(int i=right-1;i>=left;i--){
x.add(matrix[bottom][i]);
}
}
if(left!=right){
for(int i=bottom-1;i>=top+1;i--){
x.add(matrix[i][left]);
}
}
left++;right--;top++;bottom--;
}
return x;
}
}
出现的错误:
问题一:自己在循环条件时写错了
while(left<right&&top<bottom){
原来写成了while(row>0&&col>0) 这个表达式使得程序陷入了死循环。
问题二:在给上下左右定值时 把行和列的长度没有设置错误:right=row-1;
问题三:在边界时候 i 值不是设置为从0开始而是要设置为left或者top;
问题四:add加入值得时候 列和行弄混了!!!