码迷,mamicode.com
首页 > 其他好文 > 详细

Snake Sequence

时间:2014-11-21 12:16:50      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   strong   on   

Problem

You are given a grid of numbers. A snake sequence is made up of adjacent numbers such that for each number, the number on the right or the number below it is +1 or -1 its value. For example,

1 3 2 6 8
-9 7 1 -1 2
1 5 0 1 9

In this grid, (3, 2, 1, 0, 1) is a snake sequence. Given a grid, find the longest snake sequences and their lengths 

(so there can be multiple snake sequences with the maximum length).

Solution

 1 public int findSnakeSequence(int[][] matrix) {
 2 //        List<List<Integer>> res = ArrayList<ArrayList<Integer>>();
 3     if(matrix == null || matrix.length == 0) {
 4         return -1;
 5     }
 6     int m = matrix.length;
 7     int n = matrix[0].length;
 8     
 9     int[][] dp = new int[m][n];
10     int globalMax = 0;
11     
12     //initialize
13     dp[0][0] = 1;
14     for(int i=1; i<n; i++) {
15         if(Math.abs(matrix[0][i] - matrix[0][i-1]) == 1) 
16             dp[0][i] = dp[0][i-1] + 1;
17         else
18             dp[0][i] = 1;
19     }
20     
21     for(int i=1; i<m; i++) {
22         if(Math.abs(matrix[i][0] - matrix[i-1][0]) == 1) 
23             dp[i][0] = dp[i-1][0] + 1;
24         else
25             dp[i][0] = 1;
26     }
27     
28     for(int i=1; i<m; i++) {
29         for(int j=1; j<n; j++) {
30             int max = 1;
31             if(Math.abs(matrix[i][j] - matrix[i][j-1]) == 1)
32                 max = dp[i][j-1] + 1;
33             if(Math.abs(matrix[i][j] - matrix[i-1][j]) == 1)
34                 max = Math.max(max, dp[i-1][j] + 1);
35             dp[i][j] = max;
36             globalMax = Math.max(max, globalMax);
37         }
38     }
39     
40     for (int i = 0; i < m; i++) {
41     for (int j = 0; j < n; j++) {
42         System.out.print(dp[i][j] + " ");
43     }
44     System.out.print("\n");
45     }
46     
47     return globalMax;
48         
49 }

 

Snake Sequence

标签:style   blog   io   ar   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/superbo/p/4112177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!