Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class sherlocked {
  5. public static int N, M;
  6. public static int[][] grid, visited;
  7. public static int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
  8. public static int ret = 1;
  9. public static void main(String[] args) throws IOException{
  10. FastScanner kb = new FastScanner(new File("sherlocked.in"));
  11. //Scanner kb = new Scanner(System.in);
  12. PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sherlocked.out")));
  13. N = kb.nextInt(); M = kb.nextInt(); grid = new int[N][M]; visited = new int[N][M];
  14. for(int i = 0; i < N; i++)
  15. for(int j = 0; j < M; j++)
  16. grid[i][j] = kb.nextInt();
  17. for(int i = 0; i < N; i++)
  18. for(int j = 0; j < M; j++){
  19. if(visited[i][j] > 0) continue;
  20. recurse(i, j);
  21. }
  22. out.println(ret);
  23. out.close();
  24. }
  25. public static int recurse(int r, int c){
  26. if(visited[r][c] > 0) return visited[r][c];
  27. int res = 1;
  28. for(int a = 0; a < 4; a++){
  29. int nr = dx[a]+r; int nc = dy[a]+c;
  30. if(inBounds(nr, nc) && grid[nr][nc] == grid[r][c]-1)
  31. res = Math.max(res, recurse(nr, nc)+1);
  32. }
  33. ret = Math.max(ret, res);
  34. return visited[r][c] = res;
  35. }
  36. public static boolean inBounds(int x, int y){ return x > -1 && y > -1 && x < N && y < M; }
  37. static class FastScanner{
  38. BufferedReader br;
  39. StringTokenizer st;
  40. public FastScanner(File i) throws IOException{
  41. br = new BufferedReader(new FileReader(i));
  42. st = new StringTokenizer("");
  43. }
  44. public String next() throws IOException {
  45. if(st.hasMoreTokens())
  46. return st.nextToken();
  47. else
  48. st = new StringTokenizer(br.readLine());
  49. return next();
  50. }
  51. public int nextInt() throws IOException {
  52. return Integer.parseInt(next());
  53. }
  54. public String nextLine() throws IOException {
  55. if(!st.hasMoreTokens())
  56. return br.readLine();
  57. String ret = st.nextToken();
  58. while(st.hasMoreTokens())
  59. ret += " " + st.nextToken();
  60. return ret;
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement