0
Help us understand the problem. What are the problem?

posted at

566 解答

参考:
Nick White

解答

	public int[][] matrixReshape(int[][] mat, int r, int c) {

		int m = mat.length;
		int n = mat[0].length;

		if (m * n != r * c)
			return mat;// もし引数のサイズと出力するサイズが合わないとき

		int[][] ans = new int[r][c];
		int row_ans = 0; // 出力用の行
		int col_ans = 0; // 出力用の列
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				ans[row_ans][col_ans] = mat[i][j];

				col_ans++;

				if (col_ans == c) { //ココがやややこしい
					col_ans = 0;
					row_ans++;
				}

			}

		}

		return ans;

	}

Array の出力方法

1D Array

System.out.println(Arrays.toString(1DArray));

2D Array

System.out.println(Arrays.deepToString(2DArray));

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?