566. Reshape the Matrix

566. Reshape the Matrix

class Solution {
	public int[][] matrixReshape(int[][] nums, int r, int c) {
		if (nums.length * nums[0].length != r * c)
			return nums;
		int[][] out = new int[r][c];

		boolean[][] visited = new boolean[r][c];

		for (int i = 0; i < nums.length; i++)
			for (int j = 0; j < nums[i].length; j++) {
				searchEmptyPlace: {
					for (int a = 0; a < out.length; a++)
						for (int b = 0; b < out[a].length; b++)
							if (!visited[a][b]) {
								out[a][b] = nums[i][j];
								visited[a][b] = true;
								break searchEmptyPlace;
							}
				}
			}

		return out;
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s