您的位置:首页 > 编程语言

求最大蛇的长度 本题只是笔记 代码是错的

2017-01-17 16:44 295 查看
package work;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class anaconda {

 static class Node {

  int x;

  int y;

  int step;

 }

 static int N, M, maxlen;

 static int[][] data;

 static Node[] queue;

 static int[] Dx = { -1, 0, 1, 0 };

 static int[] Dy = { 0, 1, 0, -1 };

 static int counts;

 static int[] res;

 public static void main(String[] args) throws FileNotFoundException {

  /* Scanner sc=new Scanner(System.in); */

  Scanner sc = new Scanner(new File("src/anaconda"));

  while (true) {

   N = sc.nextInt();

   M = sc.nextInt();

   data = new int
[M];

   res = new int[N * M];

   queue = new Node[N * M];

   if (N == 0 && M == 0) {

    break;

   }

   for (int i = 0; i < N; i++) {

    for (int j = 0; j < M; j++) {

     data[i][j] = sc.nextInt();

    }

   }

   counts = 0;

   for (int n = 0; n < N; n++) {

    for (int m = 0; m < M; m++) {

     if (data[m]
== 1) {

      counts++;

      res[counts] = bfs(m, n, 1);

     }

    }

   }

   maxlen = 0;

            for (int i = 0; i < N*M; i++) {

    if(maxlen<res[i]){maxlen=res[i];}

   }

   System.out.println(maxlen);

  }

 }

 private static int bfs(int n, int m, int step) {

  int head = 0;

  int tail = 0;

  int count = 0;

  Node n1 = new Node();

  n1.x = n;

  n1.y = m;

  n1.step = step;

  queue[tail++] = n1;

  while (head < tail) {

   for (int i = 0; i < 4; i++) {

    int dx = queue[head].x + Dx[i];

    int dy = queue[head].x + Dy[i];

    if (dx < 0 || dy >= N || dy < 0 || dy >= M) {

     break;

    }

    if (dx >= 0 && dy < N && dy >= 0 && dy < M && data[dx][dy] == 1) {

     data[dx][dy] = 2;

     Node n2 = new Node();

     n2.x = dx;

     n2.y = dy;

     n2.step = queue[head].step + 1;

     queue[tail++] = n2;

     count++;

    }

   }

   head++;

  }

  return count;

 }

}

、、input

5 5

0 0 0 1 0

0 0 0 1 1

1 1 1 0 0

0 0 1 0 0

0 0 0 0 0

10 10

0 0 0 0 0 1 0 0 0 0

1 1 1 1 0 1 1 1 1 0

1 0 0 1 0 0 0 0 1 1

1 1 0 1 0 0 0 0 0 0

0 1 0 1 0 0 0 0 0 0

1 1 0 1 0 0 0 0 0 0

0 0 0 1 0 0 0 0 0 0

0 0 0 1 1 1 1 0 0 0

0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 1 0 0 0

10 10

0 0 0 0 0 1 0 0 0 0

1 0 0 0 0 1 1 0 0 0

1 0 0 0 0 0 0 0 0 0

1 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 0 0 1 0 0 0 0 0 0

0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 1 0 0 0

0 0

、、output

2

2

1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: