2018头条笔试题-世界杯问题

2018-08-13 07:38:02来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

题目:

输入如下面所示:

前一行是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);
        }
   
    }

}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Servlet HttpRequest 中【getAttribute】和【getParameter】的区

下一篇:Java与微信相关