文章目录
- Z形打印
- 边界为1的最大子方阵
Z形打印
package 每日算法学习打卡.算法打卡.七月份.七月二十七号;
public class test1 {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
print(matrix);
}
static void print(int[][] matrix) {
int r = 0, m = matrix.length;
int l = 0, n = matrix[0].length;
boolean l2r = true;
while (r < m && l < n) {
if (l2r) {
System.out.println(matrix[r][l] + " ");
//如果在走上坡路
if (r == 0 && l < n - 1) {
l2r = !l2r;
l++;
continue;
//如果已经走到末尾了,行号就进行减一操作
} else if (r > 0 && l == n - 1) {
l2r = !l2r;
r++;
continue;
//其余的情况都是在走上坡路
} else {
r--;
l++;
}
} else {
//如果是在走下坡路
System.out.println(matrix[r][l] + " ");
//如果走到左边界的时候,就向下走一格
if(l == 0 && r <m-1){
l2r = !l2r;
r++;
continue;
}else if( r == m-1){
l2r = !l2r;
l++;
continue;
}else{
r++;
l--;
}
}
}
}
}
边界为1的最大子方阵
package 每日算法学习打卡.算法打卡.七月份.七月二十七号;
public class test2 {
public static int solve(int[][] matrix, int N) {
int n = N; // 阶数
boolean flag = false;
while (n > 0) {
for (int i = 0; i < N; i++, flag = false) {
if (i + n > N)
break;
for (int j = 0; j < N; j++, flag = false) {
if (j + n > N)
break;
// 当前节点开始查看是否满足均为1
int r = i, c = j;
while (c < j + n) { // 往右走
if (matrix[r][c] == 0) {
flag = true;
break;
}
c++;
}
if (flag) {
continue;
}
c--; // 复原
while (r < i + n) { // 往下走
if (matrix[r][c] == 0) {
flag = true;
break;
}
r++;
}
if (flag) {
continue;
}
r--;
while (c >= j) { // 往左走
if (matrix[r][c] == 0) {
flag = true;
break;
}
c--;
}
if (flag) {
continue;
}
c++;
while (r >= i) { // 往上走
if (matrix[r][c] == 0) {
flag = true;
break;
}
r--;
}
if (flag) {
continue;
}
r++;
return n;
}
}
n--;
}
return n; // 全是0,直接返回
}
public static void main(String[] args) {
int[][] matrix = {
{0, 1, 1, 1, 1},
{0, 1, 0, 0, 1},
{0, 1, 0, 0, 1},
{0, 1, 1, 1, 1},
{0, 1, 0, 1, 1}
};
int res = solve(matrix, 5);
System.out.println("result: " + res);
}
}