The path in the matrix of the offer (65) of the sword

Source: Internet
Author: User

Title Description

Please design a function to determine if there is a path in a matrix that contains all characters of a string. The path can start from any grid in the matrix, and each step can move to the left, right, up, and down a grid in the matrix. If a path passes through a lattice in the matrix, the path can no longer enter the grid. For example a B c e s f C s a D-e matrix contains a path to the string "bcced", but the matrix does not contain a "ABCB" path, because the first character B of the string occupies the second lattice in the first row of the matrix, and the path cannot enter the lattice again.

Code:

/** uses a state array to save previously accessed characters, then press up, down, left, and right recursively */public class solution {public boolean haspath (char[] matrix, int rows, int cols,        Char[] str) {int flag[] = new Int[matrix.length];  for (int i = 0; i < rows; i++) {for (int j = 0; J < cols; J + +) {if (For helper (matrix, rows,            Cols, I, J, str, 0, flag) return true;    }} return false; } Private Boolean helper (char[] matrix, int rows, int cols, int i, Int j, char[] str, int k, int[] flag) {int        index = i * cols + j;  if (I < 0 | | I >= rows | | J < 0 | | J >= cols | | matrix[index]! = Str[k] | | flag[index] = = 1) return        False        if (k = = str.length-1) return true;        Flag[index] = 1;  if (helper (matrix, rows, cols, I-1, J, str, K + 1, flag) | | Helper (Matrix, rows, cols, i + 1, j, str, k + 1, flag) | | Helper (matrix, rows, cols, I, j-1, str, k + 1, flag) | | HelpeR (Matrix, rows, cols, I, j + 1, str, k + 1, flag)) {return true;        } Flag[index] = 0;    return false; }}


The path in the matrix of the offer (65) of the sword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.