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

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[N][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][n] == 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值