中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
第二题解法,只是这个是flower and garden
- ublic class FlowersInGarden {
- public static void main(String[] args) {
- char[][] matrix = {{'f', 'x', 'x', 'w', 'f'},
- {'f', 'f', 'x' ,'x' ,'x'},
- {'x', 'x', 'f', 'w', 'f'},
- {'f', 'f', 'x', 'w', 'x'}};
- maxFlowersInGarden(matrix);
- }
-
- public static int maxFlowersInGarden(char[][] matrix) {
- if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
- return 0;
- }
- int m = matrix.length;
- int n = matrix[0].length;
-
- int[][] res = new int[m][n];
- for (int i = 0; i < m; i++) {
- int count = 0;
- int j = 0;
- int start = 0;
- while (j < n) {
- if (matrix[i][j] == 'f') {
- count++;
- } else if (matrix[i][j] == 'w') {
- for (int k = start; k < j; k++) {
- res[i][k] = count;
- }
- start = j + 1;
- count = 0;
- }
- j++;
- }
- for (int k = start; k < j; k++) {
- res[i][k] = count;
- }
- }
- for (int j = 0; j < n; j++) {
- int count = 0;
- int i = 0;
- int start = 0;
- while (i < m) {
- if (matrix[i][j] == 'f') {
- count++;
- } else if (matrix[i][j] == 'w') {
- for (int k = start; k < i; k++) {
- res[k][j] += count;
- }
- start = i + 1;
- count = 0;
- }
- i++;
- }
- for (int k = start; k < i; k++) {
- res[k][j] += count;
- }
- }
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (matrix[i][j] == 'f') {
- res[i][j] -= 1;
- }
- }
- }
- int max = 0;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- System.out.print(res[i][j] + " ");
- max = Math.max(max, res[i][j]);
- }
- System.out.println();
- }
-
-
- return max;
- }
- }
复制代码 |
|