image.png

    1. public class Vector2D{
    2. private int[][] matrix;
    3. private int row;
    4. private int col;
    5. private boolean curUse;
    6. public Vector2D(int[][] v) {
    7. matrix = v;
    8. row = 0;
    9. col = -1;
    10. curUse = true;
    11. hasNext();
    12. }
    13. public int next() {
    14. int ans = matrix[row][col];
    15. curUse = true;
    16. hasNext();
    17. return ans;
    18. }
    19. public boolean hasNext() {
    20. if (row == matrix.length) {
    21. return false;
    22. }
    23. // 重复多次调用弄hasNext的时候
    24. if (!curUse) {
    25. return true;
    26. }
    27. //(row, col)已经用过了
    28. if (col < matrix[row].length) {
    29. col++;
    30. } else {
    31. col = 0;
    32. do {
    33. row++;
    34. } while (row < matrix.length && matrix[row].length == 0);
    35. }
    36. //新的row, col
    37. if (row != matrix.length) {
    38. curUse = false;
    39. return true;
    40. } else {
    41. return false;
    42. }
    43. }
    44. }