二维数组最大连续和

最大相连男生

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static int row;
    static int col;
    static int[][] arr;
    static int[][] offsets = {{0, 1}, {1, 0}, {1, -1}, {1, 1}};  //  横、纵、主对角线【左上角 ==> 右下角】、反对角线
    static int res;

    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
        String[] split = in.nextLine().split(",");
        row = Integer.parseInt(split[0]);
        col = Integer.parseInt(split[1]);
        arr = new int[row][col];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < row; i++) {
           sb.append(in.nextLine() + ",");
        }
        String[] temp = sb.toString().substring(0, sb.length() - 1) .replace("M", "1").replace("F", "0").split(",");
        int index = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                arr[i][j] = Integer.parseInt(temp[index++]);
            }
        }
       for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (arr[i][j] == 1) {  //  查看每个 1 的点
                    for (int[] offset : offsets) {
                        getResult(offset, i, j);  //  4个方向能到达的最大值
                    }
                }
            }
        }
        System.out.println(res);
    }

   public static void getResult(int[] offset, int i, int j){
        int count = 0;
        while (i >=0 && i < row && j >= 0 && j < col){
            if (arr[i][j] == 1){
                count++;
            }else {
               break;
            }
            i += offset[0];
            j += offset[1];
        }
        res = Math.max(res, count);
    }
}
posted @ 2023-09-15 15:05  爱新觉罗LQ  阅读(6)  评论(0编辑  收藏  举报