PKU_ACM_3620_Avoid The Lakes

 http://acm.pku.edu.cn/JudgeOnline/problem?id=3620 原題

 

題目大意就是在一個N*M的網格區域內,找出有相同特徵的最大的一塊區域

具體實現用遞歸,但效率不是很高

 

下載是源碼(java):

 

  1. import java.io.*;
  2. import java.util.*;
  3. public class Main
  4. {
  5.  static int[][] grids;
  6.  public static void main(String[] args) throws Exception
  7.  {
  8.   readFile();
  9.   for(int i=1; i<grids.length; i++)
  10.   {
  11.    for(int j=1; j<grids[i].length; j++)
  12.    {
  13.     if(grids[i][j]==1)
  14.     {
  15.      process(i,j);
  16.      if(tempSum>sum)
  17.       sum = tempSum;
  18.      tempSum = 0;
  19.     }
  20.    }
  21.   }
  22.   System.out.print(sum);
  23.  }
  24.  static void readFile() throws Exception
  25.  {
  26.   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  27.   StringTokenizer st = new StringTokenizer(br.readLine()," ");
  28.   int row = Integer.valueOf(st.nextToken());
  29.   int col = Integer.valueOf(st.nextToken());
  30.   int k = Integer.valueOf(st.nextToken());
  31.   grids = new int[row+1][col+1];
  32.   int count = 0;
  33.   while(count<k)
  34.   {
  35.    st = new StringTokenizer(br.readLine()," ");
  36.    grids[Integer.valueOf(st.nextToken())][Integer.valueOf(st.nextToken())] = 1;
  37.    count++;
  38.   }
  39.   br.close();
  40.   
  41.  }
  42.  static int tempSum = 0;
  43.  static int sum = -1;
  44.  static void process(int x,int y)
  45.  {
  46.   if(x<1 || x>=grids.length || y<1 || y>=grids[0].length)
  47.    return;
  48.   if(grids[x][y]!=1)
  49.    return;
  50.   tempSum++;
  51.   grids[x][y] = 0;
  52.   process(x-1,y);
  53.   process(x,y+1);
  54.   process(x+1,y);
  55.   process(x,y-1);
  56.  }
  57. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章