2018头条笔试题-世界杯问题
Posted xiangkejin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2018头条笔试题-世界杯问题相关的知识,希望对你有一定的参考价值。
题目:
输入如下面所示:
前一行是m行、n列
后面是这个m行n列的数据,从任意一个1出发,可上下、左右、斜角遍历
要求输出有多少个连通图、连通图中包含的最大连通个数。
10,10
0,0,0,0,0,0,0,0,0,0
0,0,0,1,1,0,1,0,0,0
0,1,0,0,0,0,0,1,0,1
1,0,0,0,0,0,0,0,1,1
0,0,0,1,1,1,0,0,0,1
0,0,0,0,0,0,1,0,1,1
0,1,1,0,0,0,0,0,0,0
0,0,0,1,0,1,0,0,0,0
0,0,1,0,0,1,0,0,0,0
0,1,0,0,0,0,0,0,0,0
package algorithm; import java.util.Scanner; public class Toutiao { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.next(); String[] s1Arr= s1.split(","); int x = Integer.valueOf(s1Arr[0]); int y = Integer.valueOf(s1Arr[1]); int[][] a = new int[x][y]; for(int i = 0; i < x; i++){ String s = sc.next(); String[] sArr = s.split(","); for(int j = 0;j<y;j++) a[i][j]= Integer.valueOf(sArr[j]); } int rt[] = new int [2]; rt=getCount(a,x,y); System.out.println(rt[0]); System.out.println(rt[1]); } public static int[] getCount(int[][] A,int x,int y) { int a[] = new int [2]; int max =0; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (A[i][j] == 1) { a[0]++; int count = 0; pathcount =0; erase(A, i, j,count); if(pathcount >max) max=pathcount; } } } a[1]= max; return a; } public static int pathcount =0; public static void erase(int[][] A, int i, int j,int count) { pathcount++; count++; A[i][j] = 0; while (i - 1 >= 0 && A[i - 1][j] == 1) { //下 erase(A, i - 1, j,count); } while (i + 1 < A.length && A[i + 1][j] == 1) { // 上 erase(A, i + 1, j,count); } while (j - 1 >= 0 && A[i][j - 1] == 1) { //左 erase(A, i, j - 1,count); } while (j + 1 < A[0].length && A[i][j + 1] == 1) { //右 erase(A, i, j + 1,count); } while (i - 1 >= 0 && j-1 >=0 && A[i-1][j - 1] == 1) { //左上 erase(A, i-1, j -1,count); } while (i + 1 < A.length && j+1 <A[0].length && A[i+1][j + 1] == 1) { //右下 erase(A, i+1, j +1,count); } while (i - 1 >= 0 && j+1 <A[0].length && A[i-1][j + 1] == 1) { //右上 erase(A, i-1, j +1,count); } while (i + 1 < A.length && j-1 >=0 && A[i+1][j - 1] == 1) { //左下 erase(A, i+1, j -1,count); } } }
以上是关于2018头条笔试题-世界杯问题的主要内容,如果未能解决你的问题,请参考以下文章