Find the “balance number” in a matrix

The balance number in a matrix is defined as the number whose sum of the elements in rows above it equals the sum of elements in rows below, and same for the columns. For the rows, we make two arrays, one stores the sum of all elements of rows up to the current row index, the other stores sum of all elements from the current row index to the end. Same for the columns, Then we can simply scan all the elements and look into those arrays to find out if it is balanced or not.

public class Test {
	public static ArrayList<String> balanceNum(int [][] matrix) {
		int noCol = matrix[0].length;
		int noRow = matrix.length;
		int [] sumRow = new int [noRow];
		int [] sumCol = new int [noCol];
		for(int r = 0; r < noRow; r++) {
			for (int c = 0; c < noCol; c++) {
				sumRow[r] += matrix[r][c];
			}
		}
		for (int c = 0; c < noCol; c++) {
			for (int r = 0; r < noRow; r++) {
				sumCol[c] += matrix[r][c];
			}
		}
		
		int [] dpRabove = new int [noRow];
		dpRabove[0] = sumRow[0];
		for (int i = 1; i < noRow; i++) {
			dpRabove[i] = dpRabove[i-1] + sumRow[i];
		}
		
		int [] dpRbelow = new int [noRow];
		dpRbelow[noRow-1] = sumRow[noRow-1];
		for (int i = noRow - 2; i >= 0; i--) {
			dpRbelow[i] = dpRbelow[i+1] + sumRow[i];
		}
		
		int [] dpCabove = new int [noCol];
		dpCabove[0] = sumCol[0];
		for (int i = 1; i < noCol; i++) {
			dpCabove[i] = dpCabove[i-1] + sumCol[i];
		}
		
		int [] dpCbelow = new int [noCol];
		dpCbelow[noCol - 1] = sumCol[noCol-1];
		for (int i = noCol - 2; i >= 0; i--) {
			dpCbelow[i] = dpCbelow[i+1] + sumCol[i];
		}
		
		ArrayList<String> res = new ArrayList<String>();
		for (int r = 1; r < noRow-1; r++) {
			for (int c = 1; c < noCol-1; c++) {
				if (dpCabove[c-1] == dpCbelow[c+1] && dpRabove[r-1] == dpRbelow[r+1]) { 
					String tmp = new String("" + (char)(r + '0') + "," + (char)(c + '0'));
					res.add(tmp);
				}
			}
		}
		return res;
	}
	public static void main(String[] args) {
		Test t = new Test();
		int [] a1 = {30, 10, 50, '#', '#', '#', 20, 45, '#', '#', 36, '#', '#'};
		int [][] a = {{1,1,2}, {3,2,3}, {2,1,1}};
		System.out.println(balanceNum(a));
		
	}
}

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 )

Google+ photo

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

Connecting to %s