No. 34 - String Path in Matrix

No. 34 - String Path in Matrix


Question: How to implement a function to check whether there is a path for a string in a matrix of characters?  It moves to left, right, up and down in a matrix, and a cell for a movement. The path can start from any entry in a matrix. If a cell is occupied by a character of a string on the path, it cannot be occupied by another character again.

For example, the matrix below with three rows and four columns has a path for the string “BCCED” (as highlighted in the matrix). It does not have a path for the string “ABCB”, because the first “B” in the string occupies the “B” cell in the matrix, and the second “B” in the string cannot enter into the same cell again.

A
B
C
E
S
F
C
S
A
D
E
E

Analysis: It is a typical problem about backtracking, which can be solved by storing a path into a stack.

Firstly, it is necessary to define a structure for 2-D positions, as below:

struct Position
{
     int x;
     int y;
};

The movements of four directions can be defined accordingly:

Position up = {0, -1};
Position right = {1, 0};
Position down = {0, 1};
Position left = {-1, 0};
Position dir[] ={up, right, down, left};

Since paths can start from any entry in a matrix, we have to scan every cell to check whether the character in it is identical to the first character of the string. If it is identical, we begin to explore a path from such a cell.

A path is defined as a stack. When a cell on path is found, we push its position into the stack. Additionally, we also define a matrix of Boolean masks to void entering a cell twice, which is denoted as visited. Based on these considerations, the skeleton of solution can be implemented as the following:

bool hasPath( char* matrix,  int rows,  int cols,  char* str)
{
     if(matrix == NULL || rows < 1 || cols < 1 || str == NULL)
         return  false;

     bool *visited =  new  bool[rows * cols];
    memset(visited, 0, rows * cols);

     for( int row = 0; row < rows; ++row)
    {
         for( int column = 0; column < cols; ++column)
        {
             if(matrix[row * cols + column] != str[0])
                 continue;

            std::stack<Position> path;
            Position position = {column, row};
            path.push(position);
            visited[row * cols + column] =  true;

             if(hasPathCore(matrix, rows, cols, str, path, visited))
                 return  true;
        }
    }

     return  false;
}

Now let us analyze how to explore a path in details. Supposing we have already found  k characters on a path, and we are going to explore the next step. We stand at the cell corresponding to the  k thcharacter of the path, and check whether the character in its neighboring cell at up, right, down, and left side is identical to the ( k+1) th character of the string.

If there is a neighboring cell whose value is identical to the ( k+1) th character of the string, we continue exploring the next step.

If there is no such a neighboring cell whose value is identical to the ( k+1) th character of the string, it means the cell corresponding to the  k th character should not on a path. Therefore, we pop it off a path, and start to explore other directions on the ( k-1) th character.

Based on the analysis above, the function hasPathCore can be defined as:

bool hasPathCore( char* matrix,  int rows,  int cols,  char* str, std::stack<Position>& path,  bool* visited)
{
     if(str[path.size()] ==  '\0')
         return  true;

     if(getNext(matrix, rows, cols, str, path, visited, 0))
         return hasPathCore(matrix, rows, cols, str, path, visited);

     bool hasNext = popAndGetNext(matrix, rows, cols, str, path, visited);
     while(!hasNext && !path.empty())
        hasNext = popAndGetNext(matrix, rows, cols, str, path, visited);

     if(!path.empty())
         return hasPathCore(matrix, rows, cols, str, path, visited);
   
     return  false;
}

The function getNext is defined to explore the ( k+1) th character on a path. When it returns true, it means the ( k+1) th character on a path has been found. Otherwise, we have to pop the  k thcharacter off. The function getNext is implemented as below:

bool getNext( char* matrix,  int rows,  int cols,  char* str, std::stack<Position>& path, bool* visited,  int start)
{
     for( int i = start; i <  sizeof(dir) /  sizeof(Position); ++i)
    {
        Position next = {path.top().x + dir[i].x, path.top().y + dir[i].y};
         if(next.x >= 0 && next.x < cols
            && next.y >=0 && next.y < rows
            && matrix[next.y * cols + next.x] == str[path.size()]
            && !visited[next.y * cols + next.x])
        {
            path.push(next);
            visited[next.y * cols + next.x] =  true;

             return  true;
        }
    }

     return  false;
}

When we found that the  k th character should not be on a path, we call the functionpopAndGetNext to pop it off, and try on other directions from the ( k-1) th character. This function is implemented as below:

bool popAndGetNext( char* matrix,  int rows,  int cols,  char* str, std::stack<Position>& path,  bool* visited)
{
    Position toBePoped = path.top();
    path.pop();
    visited[toBePoped.y * cols + toBePoped.x] =  false;

     bool hasNext =  false;
     if(path.size() >= 1)
    {
        Position previous = path.top();
         int deltaX = toBePoped.x - previous.x;
         int deltaY = toBePoped.y - previous.y;
         for( int i = 0; (i <  sizeof(dir) /  sizeof(Position) && !hasNext); ++i)
        {
             if(deltaX != dir[i].x || deltaY != dir[i].y)
                 continue;

            hasNext = getNext(matrix, rows, cols, str, path, visited, i + 1);
        }
    }

     return hasNext;
}

The author Harry He owns all the rights of this post. If you are going to use part of or the whole of this ariticle in your blog or webpages,  please add a reference to  http://codercareer.blogspot.com/. If you are going to use it in your books, please contact him via zhedahht@gmail.com . Thanks.

matlab读取TITLE = "fluent16.0.0 build-id: 10427" VARIABLES = "X" "Y" "Vorticity Magnitude" "Velocity" "Pressure" DATASETAUXDATA Common.DensityVar="19" DATASETAUXDATA Common.PressureVar="3" DATASETAUXDATA Common.TurbulentDynamicViscosityVar="23" DATASETAUXDATA Common.TurbulentKineticEnergyVar="12" DATASETAUXDATA Common.UVar="4" DATASETAUXDATA Common.VectorVarsAreVelocity="TRUE" DATASETAUXDATA Common.ViscosityVar="22" DATASETAUXDATA Common.VVar="7" ZONE T="Rectangular zone" STRANDID=0, SOLUTIONTIME=10.1499996 I=601, J=801, K=1, ZONETYPE=Ordered DATAPACKING=POINT DT=(SINGLE SINGLE SINGLE SINGLE SINGLE ) -9.000000358E-01 -9.000000358E-01 1.002435689E-03 1.000001550E+00 1.338337213E-01 -8.910000324E-01 -9.000000358E-01 1.308451639E-03 1.000004292E+00 1.338273883E-01 -8.820000291E-01 -9.000000358E-01 1.249879599E-03 1.000012040E+00 1.338108480E-01 -8.730000257E-01 -9.000000358E-01 9.235133766E-04 1.000025630E+00 1.337845922E-01 -8.640000224E-01 -9.000000358E-01 1.025002683E-03 1.000044823E+00 1.337496638E-01 -8.550000191E-01 -9.000000358E-01 1.331205131E-03 1.000069499E+00 1.337050945E-01 -8.460000157E-01 -9.000000358E-01 1.743018511E-03 1.000100851E+00 1.336492896E-01 -8.370000124E-01 -9.000000358E-01 1.912128180E-03 1.000138521E+00 1.335841864E-01 -8.280000091E-01 -9.000000358E-01 1.742910245E-03 1.000184178E+00 1.335078776E-01 -8.190000057E-01 -9.000000358E-01 1.830783789E-03 1.000236750E+00 1.334226429E-01 -8.100000620E-01 -9.000000358E-01 1.874378067E-03 1.000296950E+00 1.333269626E-01此类dat数据的代码
04-01
Windows系统电脑的jupyter notebook中输入R语言的以下代码,并报告下列提示,是什么情况?这种情况应该怎么?代码:# 检查R版本R.version.string# 更新所有已安装包update.packages(ask=FALSE, checkBuilt=TRUE)# 尝试指定镜像源install.packages("targazer", repos="https://cran.r-project.org/doc/manuals/r-patched/R-admin.html")提示:R version 4.4.3 (2025-02-28 ucrt)' There is a binary version available but the source version is later: binary source needs_compilationlme4 1.1-36 1.1-37 TRUEpackage 'MASS' successfully unpacked and MD5 sums checkedWarning message:"cannot remove prior installation of package 'MASS'"Warning message in file.copy(savedcopy, lib, recursive = TRUE):"problem copying D:\R-4.4.3\R-4.4.3\library\00LOCK\MASS\libs\x64\MASS.dll to D:\R-4.4.3\R-4.4.3\library\MASS\libs\x64\MASS.dll: Permission denied"Warning message:"restored 'MASS'"package 'Matrix' successfully unpacked and MD5 sums checkedWarning message:"cannot remove prior installation of package 'Matrix'"Warning message in file.copy(savedcopy, lib, recursive = TRUE):"problem copying D:\R-4.4.3\R-4.4.3\library\00LOCK\Matrix\libs\x64\Matrix.dll to D:\R-4.4.3\R-4.4.3\library\Matrix\libs\x64\Matrix.dll: Permission denied"Warning message:"restored 'Matrix'"The downloaded binary packages are in C:\Users\zhaoxr\AppData\Local\Temp\Rtmpwf4eNr\downloaded_packagesinstalling the source package 'lme4'Warning message in install.packages(update[instlib == l, "Package"], l, repos = repos, :"installation of package 'lme4' had non-zero exit status"Warning message:"unable to access index for repository https://cran.r-project.org/doc/manuals/r-patched/R-admin.html/src/contrib: cannot open URL 'https://cran.r-project.org/doc/manuals/r-patched/R-admin.html/src/contrib/PACKAGES'"Warning message:"package 'targazer' is not available for this version of RA version of this package for your version of R might be available elsewhere,see the ideas athttps://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages"Warning message:"unable to acces
03-27
JFM7VX690T型SRAM型现场可编程门阵列技术手册主要介绍的是上海复旦微电子集团股份有限公司(简称复旦微电子)生产的高性能FPGA产品JFM7VX690T。该产品属于JFM7系列,具有现场可编程特性,集成了功能强大且可以灵活配置组合的可编程资源,适用于实现多种功能,如输入输出接口、通用数字逻辑、存储器、数字信号处理和时钟管理等。JFM7VX690T型FPGA适用于复杂、高速的数字逻辑电路,广泛应用于通讯、信息处理、工业控制、数据中心、仪表测量、医疗仪器、人工智能、自动驾驶等领域。 产品特点包括: 1. 可配置逻辑资源(CLB),使用LUT6结构。 2. 包含CLB模块,可用于实现常规数字逻辑和分布式RAM。 3. 含有I/O、BlockRAM、DSP、MMCM、GTH等可编程模块。 4. 提供不同的封装规格和工作温度范围的产品,便于满足不同的使用环境。 JFM7VX690T产品系列中,有多种型号可供选择。例如: - JFM7VX690T80采用FCBGA1927封装,尺寸为45x45mm,使用锡银焊球,工作温度范围为-40°C到+100°C。 - JFM7VX690T80-AS同样采用FCBGA1927封装,但工作温度范围更广,为-55°C到+125°C,同样使用锡银焊球。 - JFM7VX690T80-N采用FCBGA1927封装和铅锡焊球,工作温度范围与JFM7VX690T80-AS相同。 - JFM7VX690T36的封装规格为FCBGA1761,尺寸为42.5x42.5mm,使用锡银焊球,工作温度范围为-40°C到+100°C。 - JFM7VX690T36-AS使用锡银焊球,工作温度范围为-55°C到+125°C。 - JFM7VX690T36-N使用铅锡焊球,工作温度范围与JFM7VX690T36-AS相同。 技术手册中还包含了一系列详细的技术参数,包括极限参数、推荐工作条件、电特性参数、ESD等级、MSL等级、重量等。在产品参数章节中,还特别强调了封装类型,包括外形图和尺寸、引出端定义等。引出端定义是指对FPGA芯片上的各个引脚的功能和接线规则进行说明,这对于FPGA的正确应用和电路设计至关重要。 应用指南章节涉及了FPGA在不同应用场景下的推荐使用方法。其中差异说明部分可能涉及产品之间的性能差异;关键性能对比可能包括功耗与速度对比、上电浪涌电流测试情况说明、GTH Channel Loss性能差异说明、GTH电源性能差异说明等。此外,手册可能还提供了其他推荐应用方案,例如不使用的BANK接法推荐、CCLK信号PCB布线推荐、JTAG级联PCB布线推荐、系统工作的复位方案推荐等,这些内容对于提高系统性能和稳定性有着重要作用。 焊接及注意事项章节则针对产品的焊接过程提供了指导,强调焊接过程中的注意事项,以确保产品在组装过程中的稳定性和可靠性。手册还明确指出,未经复旦微电子的许可,不得翻印或者复制全部或部分本资料的内容,且不承担采购方选择与使用本文描述的产品和服务的责任。 上海复旦微电子集团股份有限公司拥有相关的商标和知识产权。该公司在中国发布的技术手册,版权为上海复旦微电子集团股份有限公司所有,未经许可不得进行复制或传播。 技术手册提供了上海复旦微电子集团股份有限公司销售及服务网点的信息,方便用户在需要时能够联系到相应的服务机构,获取最新信息和必要的支持。同时,用户可以访问复旦微电子的官方网站(***以获取更多产品信息和公司动态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值