Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class TheGreedyDwarf {
- static int[] nextCellCoords(int[][] matrix, int r, int c) {
- int[] newCoords = new int[2];
- int up = 0;
- int left = 0;
- int right = 0;
- int down = 0;
- if(r - 1 >= 0) up = matrix[r -1][c];
- if(c - 1 >= 0) left = matrix[r][c -1];
- if(c + 1 < matrix[r].length) right = matrix[r][c + 1];
- if(r + 1 < matrix.length) down = matrix[r +1][c];
- if (up == 0 && left == 0 && right == 0 && down == 0) {
- newCoords[0] = -1;
- newCoords[1] = -1;
- return newCoords;
- }
- if (left >= up && left >= right && left >= down) {
- newCoords[0] = r;
- newCoords[1] = c - 1;
- return newCoords;
- }
- if (right > left && right >= up && right >= down) {
- newCoords[0] = r;
- newCoords[1] = c + 1;
- return newCoords;
- }
- if (up > left && up > right && up >= down) {
- newCoords[0] = r - 1;
- newCoords[1] = c;
- return newCoords;
- }
- if (down > left && down > right && down > up) {
- newCoords[0] = r + 1;
- newCoords[1] = c;
- return newCoords;
- }
- return newCoords;
- }
- public static void main(String[] args) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String[] inp = br.readLine().split(" ");
- int n = Integer.parseInt(inp[0]);
- int m = Integer.parseInt(inp[1]);
- int[][] matrix = new int [n][m];
- int[] start = new int[2];
- for (int i = 0; i < n; i++) {
- String[] next = br.readLine().split(" ");
- for (int j = 0; j < m; j++) {
- matrix[i][j] = Integer.parseInt(next[j]);
- if (matrix[i][j] == 0) {
- start[0] = i;
- start[1] = j;
- }
- }
- }
- // printMatrix(matrix);
- goldCount(matrix, start[0], start[1]);
- System.out.println(gold);
- }
- static int gold = 0;
- static void goldCount(int[][] matrix, int r, int c) {
- if (r == -1) {
- return;
- }
- int[] next = nextCellCoords(matrix, r, c);
- if(next[0] == -1 )return;
- gold++;
- matrix[next[0]][next[1]] --;
- goldCount(matrix, next[0], next[1]);
- }
- static void printMatrix(int[][] matr) {
- for (int i = 0; i < matr.length; i++) {
- for (int j = 0; j < matr[0].length; j++) {
- System.out.print(matr[i][j]);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement