2018-07-01 19:13:56
-
54. Spiral Matrix
问题描述:
问题求解:
螺旋输出问题,每次输出圈即可,需要注意的有两点:
(1)边界问题:这里可以取m,n的一半向上取整;(需要特别注意在取整前要除一个double类型的数,否则则会自动向下取整)
(2)单层问题:当前无法成圈的时候会出现单层的情况,这种情况必须要单独考虑。
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0) return res; int m = matrix.length; int n = matrix[0].length; for (int i = 0, j = 0; i < Math.ceil(m / 2.0) && j < Math.ceil(n / 2.0); i++, j++) { helper(matrix, i, j, res); } return res; } private void helper(int[][] matrix, int i, int j, List<Integer> res) { int m = matrix.length; int n = matrix[0].length; if (i == m - i - 1) for (int idx = j; idx <= n - j - 1; idx++) res.add(matrix[i][idx]); else if (j == n - j - 1) for (int idx = i; idx <= m - i - 1; idx++) res.add(matrix[idx][j]); else { int idx = j; for (; idx <= n - j - 1; idx++) res.add(matrix[i][idx]); idx = i + 1; for (; idx <= m - i - 1; idx++) res.add(matrix[idx][n - j - 1]); idx = n - j - 2; for (; idx >= j; idx--) res.add(matrix[m - i - 1][idx]); idx = m - i - 2; for (; idx > i; idx--) res.add(matrix[idx][j]); } }
-
59. Spiral Matrix II
问题描述:
问题求解:
public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int[] cnt = new int[]{1}; for (int i = 0, j = 0; i < Math.ceil(n / 2.0) && j < Math.ceil(n / 2.0); i++, j++) { helper(res, i, j, cnt); } return res; } private void helper(int[][] res, int i, int j, int[] cnt) { int n = res.length; if (i == n - i - 1) { for (int idx = i; idx <= n - j - 1; idx++) res[i][idx] = cnt[0]++; } else if (j == n - j - 1) { for (int idx = j; idx <= n - i - 1; idx++) res[idx][j] = cnt[0]++; } else { int idx = i; for (; idx <= n - j - 1; idx++) res[i][idx] = cnt[0]++; idx = i + 1; for (; idx <= n - i - 1; idx++) res[idx][n - j - 1] = cnt[0]++; idx = n - j - 2; for (; idx >= j; idx--) res[n - i - 1][idx] = cnt[0]++; idx = n - i - 2; for (; idx > i; idx--) res[idx][j] = cnt[0]++; } }