首页 > 解决方案 > 在矩阵中从左、右、上、下查找岛

问题描述

我已经尝试了一段时间,但我无法弄清楚。我必须编写一个程序,在矩阵中找到顶部、底部、左侧和右侧的数字并将它们打印出来。我在打印底部、左侧和右侧数字的地方制作了它,但不知道如何打印顶部的数字。

#include <iostream>

using namespace std;

int main()
{
    int a[10][10],i,j,m,n,zb,zb2,zb3,zb4;
    cin>>m>>n;
    
    for(i=0;i<n;i++){
        for(j=0;j<m;j++){
            cin>>a[i][j];
        }    
    }
    
    for(i=0;i<n;i++){
        for(j=0;j<m;j++){
            if(i+j<m-1){
                zb=a[i][j]; // first
            }
            if(i+j<m+1){
                zb2=a[i][j]; // second
            }
            if(i<j){
                zb3=a[i][j]; // third
            }        
            if(n+m<j+1){
                zb4=a[i][j]; // fourth
            }  
        }    
    }
   
    

    cout<<zb<<endl;
    cout<<zb2<<endl;
    cout<<zb3<<endl;
    cout<<zb4<<endl;

    return 0;
}

程序如何工作的图表 程序 示例

先感谢您!

标签: c++arraysmatrix

解决方案


嗯,中点定义为:
length >> 1(length + 1) / 2

最右边一列的索引是(column quantity) - 1
最底部行的索引是(row quantity) - 1

所以,地点是:

const unsigned int mid_column = MAXIMUM_COLUMNS / 2;
const unsigned int mid_row    = MAXIMUM_ROWS / 2;
std::cout << matrix[0][mid_column] << "\n"
          << matrix[mid_row][MAXIMUM_COLUMNS - 1] << "\n"
          << matrix[MAXIMUM_ROWS - 1][mid_column] << "\n"
          << matrix[mid_row][0] << "\n";

推荐阅读