顺时针打印矩阵

题目描述

对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。 给定int矩阵mat,以及它的维数n x m,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。java

测试样例

[[1, 2], [3, 4]], 2, 2

返回:[1, 2, 4, 3]

解题思路

要控制好每次的转向算法

解决方案

import java.util.*;

public class Printer {
	private enum Direction {
		RIGHT, DOWN, LEFT, UP;
	}
    
    public int[] clockwisePrint(int[][] mat, int n, int m) {

		HashSet<String> set = new HashSet<String>();

		int[] rs = new int[n * m];

		Direction dir = Direction.RIGHT;
		int i = 0, j = -1;
		int idx = 0;

		while (set.size() < rs.length) {

			if (dir == Direction.RIGHT) {
				if (j < m - 1
						&& !set.contains(String.format("%d,%d", i, j + 1))) {
					j++;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.DOWN;
				}
			}

			else if (dir == Direction.DOWN) {
				if (i < n - 1
						&& !set.contains(String.format("%d,%d", i + 1, j))) {
					i++;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.LEFT;
				}
			}

			else if (dir == Direction.LEFT) {
				if (j > 0 && !set.contains(String.format("%d,%d", i, j - 1))) {
					j--;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.UP;
				}
			}

			else if (dir == Direction.UP) {
				if (i > 0 && !set.contains(String.format("%d,%d", i - 1, j))) {
					i--;
					rs[idx++] = mat[i][j];
					set.add(String.format("%d,%d", i, j));
				} else {
					dir = Direction.RIGHT;
				}
			}
		}

		return rs;
	
    }
}

测试样例

import org.junit.Test;
import static org.junit.Assert.*;

public class ClockwisePrinterTest {
	private static ClockwisePrinter obj = new ClockwisePrinter();

	@Test
	public void test1() {
		int[][] mat = new int[][] { { 1, 2 }, { 3, 4 } };
		int n = 2, m = 2;
		int[] r = new int[] { 1, 2, 4, 3 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}

	@Test
	public void test2() {
		int[][] mat = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		int n = 3, m = 3;
		int[] r = new int[] { 1, 2, 3, 6, 9, 8, 7, 4, 5 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}

	@Test
	public void test3() {
		int[][] mat = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 },
				{ 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
		int n = 4, m = 4;
		int[] r = new int[] { 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7,
				11, 10 };
		assertArrayEquals(r, obj.clockwisePrint(mat, n, m));
	}
}
相关文章
相关标签/搜索