本文主要是介绍算法题--计算球迷群体个数最大球迷群体人数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;public class TestFansGroup {private static int rowLength;private static int colLength;//球迷二维数组,值为0或1或-1;0代表没球迷;1有球迷且未被遍历;-1有球迷但被遍历处理private static int[][] fans;//球迷群体个数private static int fanGroupNum;//最大球迷群体人数private static int maxGroupSize;//球迷计数器private static int fansCounter = 0;//辅助数组private static int[][] helper = {{-1, -1},{-1, 0},{-1, 1},{0, -1},{0, 1},{1, -1},{1, 0},{1, 1},};public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输入行数:");while (scanner.hasNext()) {String row = scanner.nextLine();rowLength = Integer.parseInt(row);System.out.println("输入列数:");String col = scanner.nextLine();colLength = Integer.parseInt(col);System.out.println("输入的行数:" + rowLength + " 列数:" + colLength + " 请输入数据");fans = new int[rowLength][colLength];fanGroupNum = 0;maxGroupSize = 0;for (int r = 0; r < rowLength; r++) {String fanRow = scanner.nextLine();if (StringUtils.isNotEmpty(fanRow)) {for (int c = 0; c < colLength; c++) {fans[r][c] = Integer.parseInt(String.valueOf(fanRow.charAt(c)));}}}System.out.println("放入数组完毕,开始扫描");for (int r = 0; r < rowLength; r++) {for (int c = 0; c < colLength; c++) {mark(r, c, 0);}}System.out.println("群体个数:" + fanGroupNum + " 最大群体人数:" + maxGroupSize);System.out.println("***************************");System.out.println("输入行数:");}scanner.close();}/*** 处理二维数组** @param r* @param c* @param step*/public static void mark(int r, int c, int step) {if (step == 0) {fansCounter = 0;}/*若该作为有球迷,则把值从1改为-1(标记成已处理);改群体球迷数量+1*/if (haveFan(r, c)) {fans[r][c] = -1;fansCounter++;} else {return;}/*以当前作为为中心,递归遍历相邻座位*/for (int i = 0; i < helper.length; i++) {int hrow = helper[i][0];int hcol = helper[i][1];mark(r + hrow, c + hcol, step + 1);}/*step==0,且当前作为有球迷且没被标记处理时,群体个数+1*/if (step == 0) {fanGroupNum++;}maxGroupSize = Math.max(fansCounter, maxGroupSize);/*特殊处理一个座位的情况*/if (rowLength == colLength && rowLength == 1) {fanGroupNum = fans[0][0] == 0 ? 0 : 1;maxGroupSize = fans[0][0] == 0 ? 0 : 1;}}/*** 标记该作为是否有球迷** @param r* @param c* @return*/public static boolean haveFan(int r, int c) {if (r >= 0 && r < rowLength&& c >= 0 && c < colLength&& fans[r][c] == 1) {return true;} else {return false;}}}
这篇关于算法题--计算球迷群体个数最大球迷群体人数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!