1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public class CodingInterview_013 { public int movingCount(int threshold, int rows, int cols) { if(threshold <= 0 || rows <= 0 || cols <= 0) return 0;
boolean[] visitFlags = new boolean[rows * cols];
return movingCountCore(threshold, rows, cols, 0, 0, visitFlags); }
public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visitFlags) { int count = 0; if(check(threshold, rows, cols, row, col, visitFlags)) { int index = row * cols + col; visitFlags[index] = true; count = 1 + movingCountCore(threshold, rows, cols, row, col + 1, visitFlags) + movingCountCore(threshold, rows, cols, row, col - 1, visitFlags) + movingCountCore(threshold, rows, cols, row + 1, col, visitFlags) + movingCountCore(threshold, rows, cols, row - 1, col, visitFlags); } return count; }
public boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visitFlags) { int index = row * cols + col; if(row >= 0 && row < rows && col >= 0 && col < cols && !visitFlags[index] && (getDigitsSum(row) + getDigitsSum(col)) <= threshold ) { return true; } return false; }
public int getDigitsSum(int num) { if(num <= 0) return 0; int sum = 0; while(num > 0) { sum += num % 10; num /= 10; } return sum; }
}
|