Top 150 Questions - 1.7

来源:互联网 发布:家装电路设计软件 编辑:程序博客网 时间:2024/04/30 23:51

1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

SetZero1()先扫描一次数组,记录下0元素的位置,然后进行设置。由于行列同时记录,那么同一行或列可能被设置多次,因此在SetZero2()中对行列分开存储。

package Question1_7;import java.awt.Point;import java.util.Stack;public class Question1_7{public static void main(String[] args){int[][] array = new int[][]{{1,0,3,4,5}, {5,6,7,8,9}, {9,0,1,2,5}, {3,4,5,6,7}};Question1_7 q = new Question1_7();q.printArray(array, 4, 5);System.out.println("After setting:");q.SetZero2(array, 4, 5);q.printArray(array, 4, 5);}public void SetZero1(int[][] array, int m, int n){Stack<Point> list = new Stack<Point>();// store row and column of 0for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (array[i][j] == 0)list.add(new Point(i,j));// set all rows and columns to 0while (!list.isEmpty()){Point point = list.pop();for (int i = 0; i < m; i++)array[i][point.y] = 0;for (int j = 0; j < n; j++)array[point.x][j] = 0; }}public void SetZero2(int[][] array, int m, int n){boolean[] row = new boolean[m];boolean[] col = new boolean[n];// store row and column of 0 separatelyfor (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (array[i][j] == 0){row[i] = true;col[j] = true; }for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (row[i] == true || col[j] == true)array[i][j]= 0; }public void printArray(int[][] array, int m, int n){for (int i = 0; i < m; i++){for (int j = 0; j < n; j++)System.out.print(array[i][j] + " ");System.out.println();}}}


 

原创粉丝点击