2015计算机学科夏令营上机考试C:二维数组右上左下遍历(规律 or BFS)
2015计算机学科夏令营上机考试C:二维数组右上左下遍历(规律 or BFS)

思路分析

方法一: 根据观察,遍历的顺序按横纵坐标之和递增访问,和相等的情况下,按横坐标递增访问。
方法二: 根据观察可得,访问的第一个永远是map[0][0],最后一个是map[row-1][col-1],并且每次都是先向右访问再向下,所以这就是两个方向:先右后下的BFS问题。

代码——方法一

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;

const int maxn = 110;
int map[maxn][maxn] = {0};

int row, col;

int main()
{
    // freopen("input.txt", "r", stdin);
    scanf("%d %d", &row, &col);
    for(int x=0; x<row; x++)
    {
        for(int y=0; y<col; y++)
        {
            scanf("%d", &map[x][y]);
        }
    }
    for(int sum=0; sum<=row+col-2; sum++)
    {
        for(int x=0; x<=sum&&x<row; x++)
        {
            if(sum-x>=0 && sum-x<col)
            {
                printf("%d\n", map[x][sum-x]);
            }
        }
    }
    // fclose(stdin);

    return 0;
}

代码——方法二

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;

struct node
{
    int x;
    int y;
};

const int maxn = 110;
int map[maxn][maxn] = {0};
bool vis[maxn][maxn] = {false};
int dx[2] = {0, 1};
int dy[2] = {1, 0};
queue<node> q;

int row, col;

bool judge(int x, int y)
{
    if(x<0 || x>=row || y<0 || y>=col)
    {
        return false;
    }
    if(vis[x][y] == true)
    {
        return false;
    }
    return true;
}

void BFS(int x, int y)
{
    node start;
    start.x = x;
    start.y = y;
    q.push(start);
    vis[x][y] = true;
    while(!q.empty())
    {
        node front = q.front();
        q.pop();
        printf("%d\n", map[front.x][front.y]);
        if(front.x==row-1 && front.y==col-1)
        {
            return ;
        }
        for(int i=0; i<2; i++)
        {
            int xx = front.x + dx[i];
            int yy = front.y + dy[i];
            if(judge(xx, yy) == true)
            {
                node temp;
                temp.x = xx;
                temp.y = yy;
                q.push(temp);
                vis[xx][yy] = true;
            }
        }
    }
}

int main()
{
    // freopen("input.txt", "r", stdin);
    scanf("%d %d", &row, &col);
    for(int x=0; x<row; x++)
    {
        for(int y=0; y<col; y++)
        {
            scanf("%d", &map[x][y]);
        }
    }
    BFS(0, 0);
    // fclose(stdin);

    return 0;
}

相关文章:

  • 2021-10-22
  • 2021-05-07
  • 2021-12-27
  • 2021-04-10
  • 2021-04-05
  • 2021-06-04
  • 2021-11-22
  • 2021-06-06
猜你喜欢
  • 2021-12-04
  • 2021-12-19
  • 2021-05-15
  • 2021-07-24
  • 2021-04-21
  • 2021-09-22
  • 2021-06-13
相关资源
相似解决方案