题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
- 思路 应当分为上下左右四步,并且设置一个boolean矩阵,来判断是否能一直走。
需要
public class printArray {
public void printArrayOver(int[][] arr) {
if(arr.length==0) return;
int row = 0;
int col = 0;
boolean[][] visited = new boolean[arr.length+1][arr[0].length+1];
for(int i=0;i<visited.length;i++){
visited[i][0] = true;
visited[i][visited.length-1]=true
}
for(int j=0;j<visited[0].length;j++){
visited[0][j] = true;
visited[visited.length-1][0]=true;
}
while(judge(arr,row,col)){
if(judge(arr,startX,startY))
right();
if(judge(arr,startX,startY))
down();
if(judge(arr,startX,startY))
left();
if(judge(arr,startX,startY))
up();
}
}
public void left(){
if(arr.length<=0) return;
while(!visited[row+1][col+1]&&col<arr[0].length&&col>=0) {
print(arr[row][col--]);
visited[row+1][col+1] = true;
}
}
public void right(){
if(arr.length<=0) return;
while(!visited[row+1][col+1]&&col<arr[0].length&&col>=0) {
print(arr[row][col++]);
visited[row+1][col+1] = true;
}
}
public void down(){
if(arr.length<=0) return;
while(!visited[row+1][col+1]&&row<arr.length&&row>=0) {
print(arr[row++][col]);
visited[row+1][col+1] = true;
}
}
public void up(){
if(arr.length<=0) return;
while(!visited[row+1][col+1]&&row<arr.length&&row>=0) {
print(arr[row--][col]);
visited[row+1][col+1] = true;
}
}
public boolean judge(int[][] arr,int row,int col){
boolean result = true;
return visited[row-1][col]&&visited[row][col-1]&&visited[row+1][col]&&visited[row][col+1];
}
}
网友评论