1.转圈打印矩阵
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int top_left_x = 0, top_left_y = 0,
bot_left_y = matrix.length - 1, bot_left_x = matrix[0].length - 1;
while (top_left_x <= bot_left_x && top_left_y <= bot_left_y) {
list.addAll(getRound(matrix, top_left_x, top_left_y, bot_left_x, bot_left_y));
top_left_x++;
top_left_y++;
bot_left_x--;
bot_left_y--;
}
return list;
}
private ArrayList<Integer> getRound(int[][] matrix, int top_left_x, int top_left_y,
int bot_right_x, int bot_right_y) {
int i = top_left_x, j = top_left_y;
ArrayList<Integer> list = new ArrayList<>();
while (j < bot_right_x) list.add(matrix[i][j++]);
while (i < bot_right_y) list.add(matrix[i++][j]);
if (top_left_x == bot_right_x || top_left_y == bot_right_y){
list.add(matrix[i][j]);
return list;
}
while (j > top_left_x) list.add(matrix[i][j--]);
while (i > top_left_y) list.add(matrix[i--][j]);
return list;
}
2.旋转正方形矩阵
3.之字形打印矩阵
4.在行列都排好序的矩阵中找数
5.求最大子矩阵和
import java.util.*;
public class SubMatrix {
public int sumOfSubMatrix(int[][] mat, int n) {
// write code here
if(mat == null || n == 0) return 0;
int max = Integer.MIN_VALUE;
int cur = 0;
int[] s = null;
for (int i = 0; i < n; i++){
s = new int[n];
for (int j = i; j < n; j++){
cur = 0;
for (int k = 0; k < n; k++){
s[k] += mat[j][k];
cur += s[k];
if(cur > max) max = cur;
if(cur < 0) cur = 0;
}
}
}
return max;
}
}