下面是这两道题的代码:
import java.util.ArrayList; import java.util.List; public class Solution { public ListspiralOrder(int[][] matrix) { List result = new ArrayList (); int i,j; //i为行数,j为列数 int count=0; // result.add(new Integer(matrix[0][0])); if(matrix.length == 0) return result; int [][]temp = new int[matrix.length][]; for(i=0;i = 0 && temp[i][j-1] == 0) {//向左 j--; temp[i][j] = 1; result.add(new Integer(matrix[i][j])); } while(i-1 >= 0 && temp[i-1][j] == 0) {//向上 i--; temp[i][j] = 1; result.add(new Integer(matrix[i][j])); } if((j+1==temp[i].length || temp[i][j+1] != 0) && (i+1 == temp.length || temp[i+1][j] != 0) && (j-1 < 0 || temp[i][j-1] != 0) && (i-1 < 0 || temp[i-1][j] != 0)) break; } return result; } public int[][] generateMatrix(int n) { int i,j,count; if(n==0) return null; int [][]res = new int[n][n]; int [][]temp = new int[n][n]; for(i=0;i = 0 && temp[i][j-1] == 0) {//向左 j--; temp[i][j] = 1; res[i][j] = count++; } while(i-1 >= 0 && temp[i-1][j] == 0) {//向上 i--; temp[i][j] = 1; res[i][j] = count++; } if((j+1==n || temp[i][j+1] != 0) && (i+1 == n || temp[i+1][j] != 0) && (j-1 < 0 || temp[i][j-1] != 0) && (i-1 < 0 || temp[i-1][j] != 0)) break; } return res; } public static void main(String args[]) { int i,j,n; //int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}}; int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; List result; result = new Solution().spiralOrder(matrix); for(i=0;i