本文主要是介绍基于Java的矩阵归零问题研究与实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天在微信公众号上看到一个矩阵归零的问题,自己编写处理了一下,现总结如下:
1、问题描述
2、解决思路:
3、代码实现:
构造一个对象Num,记录X,Y坐标及该数
public classNum {
//数值
private int num;
//X坐标
private int x;
//Y坐标
private int y;
public Num(intnum,intx,inty) {
this.num =num;
this.x =x;
this.y =y;
}
public int getNum() {
return num;
}
public void setNum(intnum) {
this.num =num;
}
public int getX() {
return x;
}
public void setX(intx) {
this.x =x;
}
public int getY() {
return y;
}
public void setY(inty) {
this.y =y;
}
}
数量方法
public classPic {
//打印图
public void printGraph(int[][]edges) {
for (introw = 0;row <edges.length;row++) {
for (intcol = 0;col <edges[row].length;col++) {
System.out.print(edges[row][col]);
System.out.print(" ");
}
System.out.println();
}
}
//加入队列
public Queue<Num>addZeroQueue(int[][]edges){
Queue<Num> zeroQueue = newConcurrentLinkedQueue<>();
for (introw = 0;row <edges.length;row++) {
for (intcol = 0;col <edges[row].length;col++) {
intdata =edges[row][col];
if (data == 0) {
Num zeroNum = newNum(data,row,col);
zeroQueue.add(zeroNum);
}
}
}
return zeroQueue;
}
//处理数据,若不包含则加入队列,行列分别置空
public int[][]handlerData(Queue<Num>resultQueue,int[][]edges){
List<Integer>rowList= newArrayList<Integer>();
List<Integer>colList= newArrayList<Integer>();
for (Numnum :resultQueue) {
int x = num.getX();
if (!rowList.contains(x)) {
rowList.add(x);
}
int y = num.getY();
if (!colList.contains(y)) {
colList.add(y);
}
}
for (inti = 0;i <rowList.size();i++) {
int row = rowList.get(i);
for (intj = 0;j <edges[row].length;j++) {
edges[row][j] = 0;
}
}
for (inti = 0;i <colList.size();i++) {
int col = colList.get(i);
for (intj = 0;j <edges.length;j++) {
edges[j][col] = 0;
}
}
return edges;
}
}
测试类:
public staticvoidmain(String[] args){
int[][]edges = { { 1, 6, 3, 2, 4, 5}, { 6, 0, 2, 5, 8, 1 }, { 3, 2, 6, 3, 4, 9 }, { 3, 5, 3, 5, 5, 3 },
{5, 8, 4, 5, 9, 5 }, { 6, 9, 6, 3, 0, 8 }, { 2, 6, 3, 6, 0, 1 } };
Picpic= newPic();
pic.printGraph(edges);
Queue<Num>resultQueue= pic.addZeroQueue(edges);
edges = pic.handlerData(resultQueue, edges);
System.out.println("---处理后---");
pic.printGraph(edges);
}
结果图示:
这篇关于基于Java的矩阵归零问题研究与实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!